在新建派生类实例时,有没有办法向基类提供构造函数参数? (即当基类构造函数对这些参数有默认值时)
例如
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/