[英]How to have C++ call overridden method after a conversion to the base class
I have a class A with method Hello:我有一个 class A 方法你好:
class A {
public:
void Hello(){
std::cout << "Hi from class A!" << std::endl;
}
};
I then have a class B that inherits class A and has its own Hello method:然后我有一个 class B 继承了 class A 并且有自己的 Hello 方法:
class B : public A {
public:
void Hello(){
std::cout << "Hi from class B!" << std::endl;
}
};
I create a new object of class B, and later cast it to be of type class A.我创建了一个新的 class B 的 object,然后将其转换为 class A 类型。
B myB;
A myA = static_cast<A>(myB);
How do I make it so myA.Hello();
我该怎么做
myA.Hello();
prints "Hi from class B?"?打印“你好,来自 class B?”?
You should use reference and can call Hello()您应该使用参考并可以调用 Hello()
B myB;
A& myA = static_cast<A&>(myB);
myA.Hello();
oupput:输出:
Hi from class A!
If you add "virtual" to Hello() of class A,如果将“虚拟”添加到 class A 的 Hello(),
virtual void Hello() {
you can get output below.您可以在下面获得 output。
Hi from class B!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.