[英]Using constructor base and member initializer list with inheritance
I have a question on how to use initializer list for constructors of a derived class that are inheriting from constructors of a base class. 我有一个问题,如何对从基类的构造函数继承的派生类的构造函数使用初始化程序列表。
This is the code that works: 这是有效的代码:
class base {
public:
base():x(0) {}
base(int a):x(a) {}
private:
int x;
};
class derived : public base {
public:
derived():base():y(0) { y=0; }
derived(int a, int b):base(a) { y=b; }
private:
int y;
};
However, I want to use the member initializer list to initialize the variables directly, and this leads to an error: 但是,我想使用成员初始化程序列表直接初始化变量,这会导致错误:
class base {
public:
base():x(0) {}
base(int a):x(a) {}
private:
int x;
};
class derived : public base {
public:
//derived():base():y(0) {} //wrong
//derived(int a, int b):base(a):y(b) {} //wrong
derived():base(), y(0) {} // corrected
derived(int a, int b): base(a), y(b) {} //corrected
private:
int y;
};
What's the right syntax for constructors that inherits from another constructor to use initializer list? 从另一个构造函数继承来使用初始化程序列表的构造函数的正确语法是什么?
Thanks :) 谢谢 :)
As noted by Dieter, you can easily have many initializers in a constructor, they simply must be separated with comma ( ,
) instead of column ( :
). 正如迪特尔指出的,你可以很容易地有许多初始化在构造函数中,他们只是必须用逗号(
,
)而不是列( :
)。
You class derived should then be : 您派生的类应为:
class derived : public base {
public:
derived():base(),y(0) {}
derived(int a, int b):base(a),y(b) {}
private:
int y;
};
derivedClass::derivedClass(argumentsSetOne, argumentsSetTwo, .....) : baseClassOne(argumentsSetOne) , baseClassTwo(argumentsSetTwo) { }
order doesn't really matter...by that i mean, you can specify argumentsSetTwo
before argumentsSetOne
in the Derived Class's Constructor's arguments field. 为了不被真正重要......我的意思是,你可以指定
argumentsSetTwo
前argumentsSetOne
在派生类的构造函数中的参数字段。 But again it should be same as specified in the prototype.... 但同样,它应该与原型中指定的相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.