c++ - "specialize"一个基对象变成派生对象?

标签 c++ c++11 object inheritance syntax

是否可以将基础对象“特化”为派生对象?

例如:

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/

相关文章:

python - 从 QTableView 获取数据

c++ - 在销毁派生成员之前在析构函数中调用公共(public)函数

C++11:typedef std::function 和参数本身

angularjs - 如何在 angularjs Controller 中使用转换器对象的值

c++ - 有没有办法让我的 win32 程序知道它启动的子进程已经崩溃(而不仅仅是退出)?

c++ - 打印较大的字符串 C++ 时出现问题

c++ - Qt 和 SQLite : filter using the elements of an array

c++ - C++0x 中的类型别名是否有替代方案?

arrays - 如果属性值存在于另一个对象数组中,则快速过滤对象数组

javascript - 如何同时声明多个对象