我有一个关于用基类指针分配派生类对象的问题...
class Base
{
void print() { cout<<"Class Base"; }
};
class Derived: public Base
{
void print() { cout<<"class Derived"; }
};
int main()
{
Base b, *bp;
Derived d, *dp;
b.print();
d.print();
bp = d; // why is this a conversion error? getting an error "cannot convert ‘Derived’ to ‘Base*’ in assignment"
bp = new B(); // this works fine...
}
是不是意味着我们只能将一个动态分配的派生类对象赋值给一个基类指针??为什么会这样???
最佳答案
bp
在这里是一个指针,您正试图将一个对象分配给它。尝试分配该对象的地址:bp = &d;
关于c++ - 在堆栈与堆上对派生类对象使用基类指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8245364/