c++ - 创建派生类实例时提供基类构造函数参数

标签 c++ constructor polymorphism new-operator parent-child

在新建派生类实例时,有没有办法向基类提供构造函数参数? (即当基类构造函数对这些参数有默认值时)

例如

class Base
{
public:
 Base::Base( string name = "" )
 : m_name( name ) {};

private
 string m_name;
};

class Derived : public Base
{
public:
 Derived::Derived() {};
};

然后我需要做这样的事情:

void main()
{
 Base* instance = new Derived( "Jeff" );
};

这显然行不通。有没有一种方法可以新建派生实例并为其基类提供构造函数参数,而无需在派生类构造函数中提供该参数。

最佳答案

Is there a way to new a derived instance and provide a constructor parameter to it's base without having to provide that parameter in the derived class constructor.

没有。

您的派生类构造函数需要获取参数,并将它们显式传递给基类构造函数。

class Derived : public Base
{
public:
 Derived::Derived(string name) : Base(name) {};
};

无论您是否使用 new 都是如此。

关于c++ - 创建派生类实例时提供基类构造函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11334598/

相关文章:

c++ - 问题重构奇怪地重复出现的模板模式

C++ 入门 : Exercises involving Sales_item. h

c++ - MFC 无法从 DLL 加载 Dlg

android - 如何使用 Kotlin 创建自定义 View 的构造函数

java - 如何使用显示方法和调用构造函数?

c++ - 类成员变量的初始化顺序

c++ - 有没有比使用 dynamic_cast 更快的在运行时检测对象类型的方法?

c++ - boost/random/uniform_int.hpp 和 boost/random/uniform_int_distribution.hpp 可以互换使用吗?

c++ - 从基类实例调用派生类方法

c++ - C++ 中一个类的多个接口(interface)