我真的对以下示例感到困惑:
#include <iostream>
class C {
public:
int a,b;
};
int main() {
C c{3,6};
std::cout<<c.a<<'\n';
std::cout<<c.b<<'\n';
return 0;
}
它工作正常并给出了预期的结果。但是如果我像下面这样修改上面的代码。
#include <iostream>
class C {
int a,b;
public:
int get_a(){
return a;
}
int get_b(){
return b;
}
};
int main(){
C c{3,6};
std::cout<<c.get_a()<<'\n';
std::cout<<c.get_b()<<'\n';
return 0;
}
在上面的程序编译器中显示了多个错误。为什么在第一个程序中允许统一初始化但在第二个程序中不允许?我哪里错了?
最佳答案
默认情况下,c++ class
成员是private
,因此无需指定即可获得私有(private)变量。因为您将类型设为私有(private),所以您不再免费获得聚合初始化,因此您需要为此类编写自己的构造函数:
class C{
C(int _a, int _b):
a(_a), b(_b)
{}
};
您只需修复cout
的命名空间,您的代码应该可以正常编译:http://coliru.stacked-crooked.com/a/1d69f4f141d2bcd2
来自标准:
[dcl.init.aggr] An aggregate is an array or a class with no user-provided constructors, no brace-or-equal-initializers for non-static data members, no private or protected non-static data members, no base classes, and no virtual functions
在第一个代码中,您只有公共(public)变量,所以代码可以工作,因为您有一个聚合,将变量设为私有(private)是导致问题的原因,因为根据上述定义,它不再是聚合。
关于c++ - 澄清 C++ 中的初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29989250/