我想出了一些令人困惑的情况。下面是它们。
#include <iostream>
using namespace std;
class Base {
public:
Base(int num) : data(num) {
cout << "BASE : " << num << endl;
}
virtual ~Base() = default;
virtual void func1() {
cout << "Base func1 called : " << data << endl;
}
virtual void func3() {
cout << "Base func3 called : " << data << endl;
}
private:
int data;
};
class Interface {
public:
Interface() {
cout << "INTERFACE : " << endl;
}
virtual ~Interface() = default;
virtual void func2() {
cout << "Interface func2 called" << endl;
}
};
class Derived : public Interface, public Base {
public:
Derived() : Base(0) {
cout << "DERIVED : hh" << endl;
}
virtual ~Derived() = default;
virtual void func1() override {
cout << "Derived fuc1 called" << endl;
}
virtual void func3() override {
cout << "Derived fuc3 called" << endl;
}
virtual void func2() override {
cout << "Derived fuc2 called" << endl;
}
};
int main() {
//Interface* a = new Derived(); // derived func2 called
//Base* a = new Derived(); // derived func1 called
//Derived* a = new Derived(); // derived func2 called
void* a = new Derived(); // derived func1 called
auto b = (Interface*)a;
b->func2();
...
}执行b->func2()时,结果因变量a的显式类型而异。
结果在评论中。
为什么在执行b->func2()时它们是不同的
发布于 2021-03-26 10:04:33
行为是未定义的,因为您不会将void *转换回实际类型。
你要么需要做
void *a = (Interface*)(new Derived());
auto b = (Interface *)a;或者在你的两个人之间添加额外的步骤
void* a = new Derived();
auto temp = (Derived *)a; // explicitly convert the void pointer to the actual type
auto b = (Interface*)temp;这相当于
void* a = new Derived();
auto b = (Interface*)((Derived *)a);无论哪种方式,如果在转换为Interface *之前没有将void *转换为Derived *,则行为是未定义的。
考虑使用其中一个_cast(例如static_cast)进行转换,而不是C风格的强制转换。
https://stackoverflow.com/questions/66809927
复制相似问题