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

时间:2012-08-20 21:11:36

标签: c++ class inheritance

我有一个带有构造函数的基类,需要一个参数(字符串)。然后我有一个派生类,它也有自己的构造函数。我想实例化派生类,并且能够设置基类的构造函数的参数。

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

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

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

我不确定在调用派生类时如何设置基类构造函数的参数。

3 个答案:

答案 0 :(得分:10)

您有两种可能性 - 内联:

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

或脱节:

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

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

更多例子:

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)
{}

初始化列表上的

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;
};

答案 1 :(得分:2)

如果您要做的只是从传递给基类构造函数的单个参数构造派生类实例,您可以这样做:

C ++ 03(我添加了显式,并通过const引用):

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

C ++ 11(获取所有基类构造函数):

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

如果你想调用不同的DerivedClass构造函数并将BaseClass构造函数调用为其他值,你也可以这样做:

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

答案 2 :(得分:0)

使用此

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

只需将参数直接传递给基类构造函数