class data
{
private:
int ID;
string address,name;
public:
data(int i,string a,string n):ID(i),address(a),name(n){}
friend class SetData;
};
class SetData
{
private:
data obj(43,"185 Awan Market","Talha"); //this is where the error happens
public:
void show()
{
cout<<"Name is: "<<obj.name<<endl;
cout<<"Address is: "<<obj.address<<endl;
cout<<"ID is: "<<obj.ID;
}
};
Run Code Online (Sandbox Code Playgroud)
C++ 03
它属于构造函数的mem-initializer:
class SetData
{
private:
data obj;
public:
SetData() : obj(43,"185 Awan Market","Talha")
{
}
// Rest goes here...
};
Run Code Online (Sandbox Code Playgroud)
C++ 11
您必须使用大括号或相同的初始化程序.
// Fine
data obj{43,"185 Awan Market","Talha"};
// Fine, too
data obj = data(43,"185 Awan Market","Talha"); //this is where the error happens
Run Code Online (Sandbox Code Playgroud)
为什么不允许使用括号,请参阅非静态数据成员初始化程序提议.向下滚动到"Kona关于标识符范围的问题"
类范围查找的动机是我们希望能够将任何内容放入非静态数据成员的初始化程序中,我们可以将其放入mem-initializer而不会显着改变语义(模数直接初始化与复制初始化) :
Run Code Online (Sandbox Code Playgroud)int x(); struct S { int i; S() : i(x()) {} // currently well-formed, uses S::x() // ... static int x(); }; struct T { int i = x(); // should use T::x(), ::x() would be a surprise // ... static int x(); };不幸的是,这使得"(表达式列表)"的初始化器在解析声明时形式不明确:
Run Code Online (Sandbox Code Playgroud)struct S { int i(x); // data member with initializer // ... static int x; }; struct T { int i(x); // member function declaration // ... typedef int x; };一种可能的解决方案是依赖现有规则,如果声明可以是对象或函数,那么它是一个函数:
Run Code Online (Sandbox Code Playgroud)struct S { int i(j); // ill-formed...parsed as a member function, // type j looked up but not found // ... static int j; };一个类似的解决方案是应用另一个现有的规则,目前只在模板中使用,如果T可以是一个类型或其他东西,那么它就是其他东西; 如果我们真的是一种类型,我们可以使用"typename":基本上
Run Code Online (Sandbox Code Playgroud)struct S { int i(x); // unabmiguously a data member int j(typename y); // unabmiguously a member function };这两种解决方案都引入了很多可能被许多用户误解的细微问题(comp.lang.c ++上的许多问题都证明了为什么"int i();"在块范围内没有声明默认初始化的int) .
本文提出的解决方案是仅允许"= initializer-clause"和"{initializer-list}"形式的初始化器.这解决了大多数情况下的歧义问题,例如:
Run Code Online (Sandbox Code Playgroud)HashingFunction hash_algorithm{"MD5"};