【发布时间】:2019-09-03 19:06:34
【问题描述】:
假设下面的例子,SecondClass 继承自 FirstClass 并且它的构造函数应该和 FirstClass 的构造函数做同样的事情。我不想重复,所以我这样做:
SecondClass(int x) : FirstClass(x) {...}
同时,我想填充name 成员,每个类应该有不同的值。在 FirstClass 中,我使用
FirstClass(int x) : BaseClass("first"), x(x) {...}
在SecondClass,我试过了
SecondClass(int x) : FirstClass(x), name("second")
编译失败(显然),因为 "class 'SecondClass' 没有任何名为 'name' 的字段"。
那么,我怎样才能实现我想要的呢?我不想在每个类构造函数中将name 作为参数传递(这似乎是一种标准方法),因为它应该是固定的,而不是由调用者设置的。
完整示例代码:
#include <iostream>
#include <string>
using namespace std;
class BaseClass {
protected:
string name;
public:
BaseClass(const string name) : name(name) {};
virtual void doSomething() {};
};
class FirstClass : public BaseClass {
protected:
int x;
public:
FirstClass(int x) : BaseClass("first"), x(x) {
cout << "FirstClass constructor, name=" << this->name << endl;
// do something more with `x`
};
virtual void doSomething() {
// do something with `x`
}
};
class SecondClass : public FirstClass {
public:
// SecondClass's constructor should do the same as FirstClass,
// but I want this->name to contain "second"
SecondClass(int x) : FirstClass(x), name("second")
{
cout << "SecondClass constructor, name=" << this->name << endl;
};
virtual void doSomething() {
// do something else with `x`
};
};
int main()
{
BaseClass *c1, *c2;
c1 = new FirstClass(1);
c2 = new SecondClass(1);
c1->doSomething();
c2->doSomething();
}
【问题讨论】:
-
“那么,我怎样才能实现我想要的?” - 将适当的构造函数添加到
FirstClass,允许您传入特定的“名称”,然后使用来自SecondClass的构造函数。 .?记住;一个类可以有多个构造函数。
标签: c++ inheritance constructor