取而代之的是:
class base
{
protected:
base( int value )
: member{value}
{}
int member = 0;
};
class derived_1 : public base
{
public:
derived_1()
: base{ 1 }
{}
};
class derived_2 : public base
{
public:
derived_2()
: base{ 2 }
{}
};
这将是有用的:
class base
{
protected:
int member = 0; // Default value
};
class derived_1 : public base
{
base::member = 1; // Instead of passing it to a base class constructor
};
class derived_2 : public base
{
base::member = 2;
};
c++1y 会支持这种或类似的语法吗?
最佳答案
不,目前没有计划允许这样做。允许初始化程序绕过基类构造函数(如果有)似乎有点奇怪;允许基类说明符包含初始化程序似乎更有意义:
class derived_1 : public base = {1}
{
};
您可能会考虑 submitting a proposal ,如果您能解释该语言将如何受益(您有具体的用例吗?)。
作为一种解决方法,您可以考虑使用类模板:
template<int I = 0>
class base { protected: int member = I; };
class derived_1: public base<1> {};
如果需要保留公共(public)基类,请使用中间基类模板:
class base { protected: int member = 0; };
template<int I>
class base_init: public base { base_init() { base::member = I; } };
class derived_1: public base_init<1> {};
不确定它是否相关,但聚合和聚合初始化的规则在 C++14 中看起来可能会改变:http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3653.html
关于c++ - c++1y 是否允许从派生类对基类变量进行类内初始化?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22705743/