是否可以将基础对象“特化”为派生对象?
例如:
class base{...
base(...) : ... {}//both have their own constructors
virtual void foo(){}
};
class derived : public base{...
void foo() override; //actual function in cpp
...};
int main(){
base x;
//is it possible to do something to x so
x.foo(); // will call derived::foo()
}
最佳答案
//is it possible to do something to x so x.foo(); // will call derived::foo()
不,你不能,至少不能以便携和符合标准的方式。
但是,您可以从 x
创建一个 derived
然后使用它。
首先,在 derived
中添加一个以 base
作为参数的构造函数。
class derived : public base{
derived(base const& b) { ... }
void foo() override; //actual function in cpp
...}
现在使用它:
derived(x).foo();
关于c++ - "specialize"一个基对象变成派生对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34570017/