gpt4 book ai didi

c++ - 嵌套类。错误 : expected parameter declarator - for inner class instance

转载 作者:行者123 更新时间:2023-11-30 00:47:03 29 4
gpt4 key购买 nike

我开始学习 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);
^

我需要这个错误背后的一个很好的解释以及如何克服这个错误。

最佳答案

您必须使用 ={} 进行就地成员初始化:

// ...
private:
Inside mOutside = 20;

括号形式会产生歧义(可能是 confused with a function declaration )。


Inside mOutside{20};

使用 clang++ 这会触发警告:

warning: private field 'mInside' is not used [-Wunused-private-field]

编译器说的有道理。奇怪的是另一种形式 (=) 缺少警告。

关于c++ - 嵌套类。错误 : expected parameter declarator - for inner class instance,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35955357/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com