C++真正的方法重载?
我有A
和B
类。当我现在创建一个 A
类型的变量并且将值设置为B
对象,然后调用WhoAreYou()
,调用A
的方法。看看这个:
class A{
public:
virtual void WhoAreYou(){
cout << "I am A!"<<endl;
}
};
class B: public A{
public:
void WhoAreYou(){
cout << "I am B!" << endl;
}
};
int main(int argc, char ** argv){
A a = B();
a.WhoAreYou(); //Output: I am A!
}
有没有办法重载该方法,以便在这种情况下调用 B 的 WhoAreYou()
方法?当我必须首先转换对象时,方法重载在我看来并没有真正意义......
感谢您的帮助!
I have the classes A
and B
. B
derives from A
and overloads the method WhoAreYou()
, when I now create a variable of type A
and set the value to a B
object and then call WhoAreYou()
, the method of A
is called. Look at this:
class A{
public:
virtual void WhoAreYou(){
cout << "I am A!"<<endl;
}
};
class B: public A{
public:
void WhoAreYou(){
cout << "I am B!" << endl;
}
};
int main(int argc, char ** argv){
A a = B();
a.WhoAreYou(); //Output: I am A!
}
Is there a way to overload the method so, that in this case the WhoAreYou()
method of B would be called? When I must cast the object first, a method overloading doesn´t really make sense in my opinion...
Thanky for your help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的“a”变量是 A,而不是 B。
A a = B();
创建一个新的临时 B,然后通过复制 B 的 A 部分来创建 A。试试这个:
Your "a" variable is an A, not a B.
A a = B();
creates a new temporary B, then creates an A by copying the A part of B.Try this:
该问题与切片有关。我对这个主题提出了完全相同的问题。
The problem has to do with slicing. I asked the exact same question with this topic.