对于没有虚函数的情况:
1.子类对象的指针可以直接赋值给父类的指针,但地址值可能会变化,也就是可能编译器给自动做了转换,具体可以看下面的例子。这也是最常规的用法。如果是多层继承,将子类的指针赋值给父类的指针时,该指针地址会自动转换到该父类的成员的开始地址的地方。
2.父类的对象的指针不能直接赋值给子类的指针,编译报错,可以需要强制转换来通过编译。这种用法一般用在创建的子类对象赋值给了父类的指针,再将父类的指针赋值给子类的指针。也就是该对象实际是子类的对象。如果是父类的对象,里面是不包含子类的内容的,所以不能强制转换为子类的指针,会发生不可预知的错误。可以使用dynamic_cast<>来转换,如果转换成功,会返回指针,如果转换失败,会返回nullptr.
3.继承类之间地址的赋值可能会引起地址的变化,这个可能是编译器自动给转换了,比如如下的例子:
https://blog.youkuaiyun.com/linkedin_35878439/article/details/79231663
所以,假如一个对象(*p)有多个父类接口A, B,当要获得某个父类接口时,可以提供通过(A*)p
或者(B*)p
来转化获得,但不能通过(A*)B
来获得。所以当某个对象有多个父类接口时,可以通过
get_interface(interface_type)函数来获得对应的接口,实现如下:
void* get_interface(interface_type)
{
if (interface_type == A) {
return ((A*)this);
} else if (interface_type == B) {
return ((B*)this);
} else {
return nullptr;
}
}
class Top
{
public :
int a = 0;
};
class Left : public Top
{
public:
int b = 0;
};
class Right : public Top
{
public:
int c = 0;
};
class Bottom : public Left, public Right
{
public:
int d = 0;
};
void test_cpp_multi_inherit()
{
Left *left_instance = new Left();
Top *top_instance = left_instance;
cout << "top_instance:" << top_instance << endl;
cout << "left_instance:" << left_instance << endl; //输出地址是一样的。
Bottom *bottom_instance = new Bottom();
Left *left_ptr = bottom_instance;
Right *right_ptr = bottom_instance;
Bottom *bb = (Bottom*)right_ptr; //这里就需要显示的强制转换
cout << "bottom_instance : " << bottom_instance << endl;
cout << "left_ptr : " << left_ptr << endl;
cout << "right_ptr" << right_ptr << endl;//这里left_ptr和right_ptr的地址就不一样。
cout << "bb: " << bb << endl; //这里bb的指针和right_ptr也不一样,会自动转换到bottom_instance的指针。
}
int main()
{
// // QCoreApplication a(argc, argv);
// printf("First Qt test program.\n");
// char buffer[4] = {'c', 'c', 'j', 0};
// std::vector<char> test_vector(buffer, buffer + 4);
// for(auto &i : test_vector) {
// printf("%c\n", i);
// }
test_cpp_multi_inherit();
return 0;
//return a.exec();
}
这篇文章也总结的蛮好,可以参考:
https://blog.youkuaiyun.com/FX677588/article/details/77727110
关于多态和动态绑定,可以参考:
https://blog.youkuaiyun.com/stay_the_course/article/details/55259801
虚函数表的介绍:
https://blog.youkuaiyun.com/songguangfan/article/details/87898915
每个类拥有一个虚函数表,每个对象拥有一个指向虚函数表的指针。
这篇文章介绍了c++类的内存结构,可以参考:
https://www.cnblogs.com/alone-striver/p/7875741.html
https://www.cnblogs.com/raichen/p/5744300.html