简体   繁体   English

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

[英]Providing base class constructor parameters when creating a derived class instance

Is there a way to provide constructor parameters to a base class when new-ing a derived class instance? 有没有办法在新建派生类实例时向基类提供构造函数参数? (That is, when the base class constructor has default values for these parameters) (也就是说,当基类构造函数具有这些参数的默认值时)

Eg 例如

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

private
 string m_name;
};

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

Then I need to do something like this: 然后我需要做这样的事情:

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

This obviously doesn't work. 这显然不起作用。 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. 有没有办法新建一个派生实例,并为它的基础提供一个构造函数参数,而不必在派生类构造函数中提供该参数。

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. 有没有办法新建一个派生实例,并为它的基础提供一个构造函数参数,而不必在派生类构造函数中提供该参数。

No. 没有。

Your derived-class constructor needs to take the arguments, and explicitly pass them down to the base-class constructor. 派生类构造函数需要获取参数,并将它们显式传递给基类构造函数。

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

This is the case regardless of whether you're using new or not. 无论您是否使用new ,都是如此。

You can't do it if you want distinct names into base class. 如果要将不同的名称放入基类,则无法执行此操作。 however distinct name is not a criteria, you can do it using passing constant literals as: 但是,不同的名称不是标准,您可以使用将常量文字传递为:

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

private
 string m_name;
};

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

OR pass default value to Derived class constructor. 或者将默认值传递给Derived类构造函数。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM