在 C++ 中从同一类中的另一个方法调用一个方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/983310/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Calling a method from another method in the same class in C++
提问by devin
I wrote a method (that works fine) for a()
in a class. I want to write another method in that class that calls the first method so:
我a()
在课堂上写了一个方法(效果很好)。我想在该类中编写另一个调用第一个方法的方法,因此:
void A::a() {
do_stuff;
}
void A::b() {
a();
do_stuff;
}
I suppose I could just rewrite b()
so b(A obj)
but I don't want to. In java can you do something like this.a()
.
我想我可以重写b()
,b(A obj)
但我不想。在 Java 中,您可以执行类似this.a()
.
I want to do obj.b()
where obj.a()
would be called as a result of obj.b()
.
我想做obj.b()
whereobj.a()
会被调用的结果obj.b()
。
采纳答案by ralphtheninja
That's exactly what you are doing.
这正是你正在做的。
回答by Eclipse
What you have should work fine. You can use "this" if you want to:
你所拥有的应该可以正常工作。如果你想,你可以使用“this”:
void A::b() {
this->a();
do_stuff;
}
or
或者
void A::b() {
this->A::a();
do_stuff;
}
or
或者
void A::b() {
A::a();
do_stuff;
}
but what you have should also work:
但你所拥有的也应该有效:
void A::b() {
a();
do_stuff;
}
回答by Tim Rupe
It looks like the code you wrote in your block would work just fine. Just make sure you have both the a() and b() methods defined inside your class properly.
看起来您在块中编写的代码可以正常工作。只要确保在类中正确定义了 a() 和 b() 方法。
回答by Todd Gamblin
What you have written there should work fine. In C++ if you call a
within b
and both are instance methods of some class A
, then you don't need to qualify it. Both a
and b
are in each others' scope.
您在那里写的内容应该可以正常工作。在 C++ 中,如果你调用a
insideb
并且两者都是某个类的实例方法A
,那么你不需要限定它。双方a
并b
在彼此的范围。
回答by MSalters
There's one case in which you might have slightly unexpected results. That is if A::a()
is virtual, obj
actually has type DerivedFromA
, and DerivedFromA::a overrides A::a
. In that case, the simple call a();
or the more verbose this->a();
will not call A::a but DerivedFromA::a().
在一种情况下,您可能会得到稍微出乎意料的结果。也就是说,如果A::a()
是虚拟的,obj
实际上有 type DerivedFromA
,并且 DerivedFromA::a 覆盖A::a
。在这种情况下,简单调用a();
或更详细的this->a();
调用将不会调用 A::a 而是 DerivedFromA::a()。
Now, this is probably intended, since class A declared a() to be virtual. But if you really don't mean it, you can ignore the virtual by writing the call either as
现在,这可能是有意的,因为类 A 将 a() 声明为虚拟的。但是如果你真的不是这个意思,你可以通过将调用编写为
void A::b()
{
A::a(); // or
this->A::a(); //Both ignore the virtual-ness of a()
}