Nested Class. error: expected parameter declarator - for inner class instance
Nested Class. error: expected parameter declarator - for inner class instance
我开始学习 C++ 中的嵌套 类,我尝试了一段我粘贴在这里的快速代码,以了解嵌套 类 的工作原理。但是编译以一些我无法弄清楚的错误结束。
文件:check.cpp
class Outside{
public:
class Inside{
private:
int mInside;
public:
Inside(const int& x):mInside(x){}
};
private:
Inside mOutside(20);
};
int main(void){
Outside o;
return 0;
}
编译时出现的错误g++ -Wall -std=c++11 -o check.out check.cpp
check.cpp:12:25: error: expected parameter declarator
Inside mOutside(20);
^
check.cpp:12:25: error: expected ')'
check.cpp:12:24: note: to match this '('
Inside mOutside(20);
^
我需要这个错误背后的一个很好的解释以及如何克服这个错误。
尝试使用这种成员初始化方式
Inside mOutside = Inside(20);
Yes, your solution worked thank you. But how? Why?
您必须使用 =
或 {}
进行就地成员初始化:
// ...
private:
Inside mOutside = 20;
括号形式会产生歧义(可能是confused with a function declaration)。
Inside mOutside{20};
使用 clang++
这会触发警告:
warning: private field 'mInside' is not used [-Wunused-private-field]
编译器说的有道理。奇怪的是另一种形式缺少警告(=
)。
我开始学习 C++ 中的嵌套 类,我尝试了一段我粘贴在这里的快速代码,以了解嵌套 类 的工作原理。但是编译以一些我无法弄清楚的错误结束。
文件:check.cpp
class Outside{
public:
class Inside{
private:
int mInside;
public:
Inside(const int& x):mInside(x){}
};
private:
Inside mOutside(20);
};
int main(void){
Outside o;
return 0;
}
编译时出现的错误g++ -Wall -std=c++11 -o check.out check.cpp
check.cpp:12:25: error: expected parameter declarator
Inside mOutside(20);
^
check.cpp:12:25: error: expected ')'
check.cpp:12:24: note: to match this '('
Inside mOutside(20);
^
我需要这个错误背后的一个很好的解释以及如何克服这个错误。
尝试使用这种成员初始化方式
Inside mOutside = Inside(20);
Yes, your solution worked thank you. But how? Why?
您必须使用 =
或 {}
进行就地成员初始化:
// ...
private:
Inside mOutside = 20;
括号形式会产生歧义(可能是confused with a function declaration)。
Inside mOutside{20};
使用 clang++
这会触发警告:
warning: private field 'mInside' is not used [-Wunused-private-field]
编译器说的有道理。奇怪的是另一种形式缺少警告(=
)。