gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:02:27 24 4
gpt4 key购买 nike

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

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

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

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

调用派生类时不知道如何设置基类构造函数的参数。

最佳答案

您有两种可能性 - 内联:

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

关于C++ - 实例化派生类并使用基类的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12045250/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com