首页 > 代码库 > c++继承赋值兼容

c++继承赋值兼容

其实还是不明白,红色部分,,,求解

#include <iostream>
#include <time.h>
using namespace std;

class B0
{
public:
void display()
{
cout<<"B0::display()"<<endl;
}
};

class B1:public B0
{
public:
void display()
{
cout<<"B1::display()"<<endl;
}
};

class B2:public B0
{
public:
void display()
{
cout<<"B2::display()"<<endl;
}
};

void fun(B0 *ptr)
{
ptr->display();
}

int main()
{
B0 b0;
B1 b1;
B2 b2;
fun(&b0);

fun(&b1);

fun(&b2);

return 0;
}

 

输出结果都是B0.....

b0=b1;

b0=b2;

结果都是一样的;

想要改变,就要用虚函数或者不要用指针

#include <iostream>
#include <time.h>
using namespace std;

class B0
{
public:
void display()
{
cout<<"B0::display()"<<endl;
}
};

class B1:public B0
{
public:
void display()
{
cout<<"B1::display()"<<endl;
}
};

class B2:public B0
{
public:
void display()
{
cout<<"B2::display()"<<endl;
}
};

 

int main()
{
B0 b0;
B1 b1;
B2 b2;
b0.display();
b1.display();
b2.display();
b2.B0::display();

return 0;
}

c++继承赋值兼容