我有以下代码。
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();
? 为什么从派生类到基类可以转换?
解决方案:
当你做 A a = B();
,复制类的构造函数 A
应在类的默认构造函数之后调用。B
(注:编译器可能会使用 抄袭埃里森).
A(const A& other)
{
}
由于,类的对象 B
可以传递给类的复制构造函数 A
允許,但你可能會遇到 对象切割.
如果你很想知道”如何将派生类对象传递给接受基类引用的方法?“,改为”。