【发布时间】:2020-08-06 16:05:12
【问题描述】:
我有以下代码:
class A {
public:
A() { cout << "A()" << endl; }
void f() { cout << "A" << endl; }
};
class B : public A {
public:
B() { cout << "B()" << endl; }
void f() { cout << "B" << endl; }
void ff() { cout << "ff()" << endl; }
};
int main()
{
A a = B();
B b;
a = b;
}
调用A a = B(); 与A a = A(); 有何不同?为什么可以从派生类转换为基类?
【问题讨论】:
-
How calling A a = B(); will be different from A a = A();?在执行此行期间,除了A之外,还将执行B构造函数。执行此行后 - 由于slicing,存储在a中的对象将完全相同。
标签: c++