gpt4 book ai didi

c++ - 奇怪的类型转换行为

转载 作者:太空宇宙 更新时间:2023-11-04 15:27:06 25 4
gpt4 key购买 nike

谁能解释一下代码的输出。

#include <iostream>

using namespace std;

class First {
public:
int a;
First() {};
First(int a) {
this->a = a;
}

int getA() {
return a;
}

virtual int getB() {
cout << "getB() from super class..." << endl;
return 0;
}
};

class Second : public First {
public:
int b;
Second(int b) {
this->b = b;
}

int getB() {
cout << "getB() from child class..." << endl;
return b;
}

};

int main() {
First* t = new Second(2);
First* cTest = dynamic_cast<First*>(t);
cout << cTest->getB() << endl;

}

我预计父类(super class)的方法会因为转换为 First 而被调用。

提前致谢

问候塞巴斯蒂安

最佳答案

getB()函数在基类中是virtual的,所以无论你有一个pointer-to-base还是pointer-to,你都能得到派生的实现-派生。

(这就是多态的全部目的。)

关于c++ - 奇怪的类型转换行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6153979/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com