简体   繁体   English

C ++ - 实例化派生类并使用基类的构造函数

[英]C++ - Instantiating derived class and using base class's constructor

I have a base class with a constructor that requires one parameter (string). 我有一个基类,其构造函数需要一个参数(字符串)。 Then I have a derived class which also has its' own constructor. 然后我有一个派生类,它也有自己的构造函数。 I want to instantiate the derived class and be able to set the parameter of the base class's constructor as well. 我想实例化派生类,并且能够设置基类的构造函数的参数。

class BaseClass {
    public:
        BaseClass (string a);
};

class DerivedClass : public BaseClass {
    public:
        DerivedClass (string b);
};

int main() {
    DerivedClass abc ("Hello");
}

I'm not sure how to set the base class constructor's parameter when calling the derived class. 我不确定在调用派生类时如何设置基类构造函数的参数。

You have two possibilities - inline: 你有两种可能性 - 内联:

class DerivedClass : public BaseClass {
public:
    DerivedClass (string b) : BaseClass(b) {}
};

or out of line: 或超出范围:

class DerivedClass : public BaseClass {
public:
    DerivedClass (string b);
};

/* ... */
DerivedClass::DerivedClass(string b) : BaseClass(b)
{}

more examples: 更多例子:

class DerivedClass : public BaseClass {
public:
    DerivedClass(int a, string b, string c);

private:
    int x;
};

DerivedClass::DerivedClass(int a, string b, string c) : BaseClass(b + c), x(a)
{}

on initializer lists: 在初始化列表上:

class MyType {
public:
    MyType(int val) { myVal = val; }    // needs int
private:
    int myVal;
};

class DerivedClass : public BaseClass {
public:
    DerivedClass(int a, string b) : BaseClass(b)
    {  x = a;  }   // error, this tries to assign 'a' to default-constructed 'x'
                   // but MyType doesn't have default constructor

    DerivedClass(int a, string b) : BaseClass(b), x(a)
    {}             // this is the way to do it
private:
    MyType x;
};

If all you want to do is construct a derived class instance from a single parameter that you pass to the base class constructor, you can to this: 如果您要做的只是从传递给基类构造函数的单个参数构造派生类实例,您可以这样做:

C++03 (I have added explicit, and pass by const reference): C ++ 03(我添加了显式,并通过const引用):

class DerivedClass : public BaseClass {
    public:
        explicit DerivedClass (const std::string& b) : BaseClass(b) {}
};

C++11 (gets all the base class constructors): C ++ 11(获取所有基类构造函数):

class DerivedClass : public BaseClass {
public:
    using BaseClass::BaseClass;
};

If you want to call different DerivedClass constructors and call the BaseClass constructor to some other value, you can do it too: 如果要调用不同的DerivedClass构造函数并将BaseClass构造函数调用为其他值,您也可以这样做:

class DerivedClass : public BaseClass {
    public:
        explicit DerivedClass () : BaseClass("Hello, World!") {}
};

Use this 用这个

 DerivedClass::DerivedClass(string b)
     : BaseClass(b)
 {
 }

just pass the parameter direct to the base class constructor 只需将参数直接传递给基类构造函数

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

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