编辑:我认为这不是this other question 的拷贝,因为另一个问题只是在构造函数中将 ()
转换为 {}
。而我注意到当构造函数在 struct
中定义时的不同行为,而不是在 class
中。 (而且,正如评论中所指出的,这是关于使用构造函数而不是编写它们。)但我以前错了。
我在辅导时遇到了构造函数的这种奇怪的(对我来说)语法:
Foo obj {i, j};
起初我认为它行不通,并告诉学生重写它——但他们坚持认为它行得通,并告诉我他们从 cplusplus.com 上提取了示例,to which I've not been able to find a reference ,所以我还是尝试了一下......它奏效了。所以我试验了一下。
我自己也研究了一下,没有找到那种constructor syntax的引用资料在 cplusplus.com 上。 (也许它有一个特定的名字?)
这是我用它做的试验。
struct Note { //A musical note.
std::string name;
double freq;
//Note(std::string s, double f): name(s), freq(f){}
//Uncomment the constructor in order to use normal constructor syntax.
};
class Journal {
public:
std::string title;
std::string message;
int idNum;
};
int main() {
Note a { "A", 440.0}; //Works with or without a constructor.
//Note a("A",440.0); //Works ***only*** with a defined constructor.
//Journal journal("hello, world", "just me, a class", 002); //Works regardless of constructor definition.
Journal journal {"hello, world", "just me, a class", 003}; //Works regardless of constructor definition.
std::cout << a.name << " " << a.freq << std::endl;
std::cout << journal.title << " " << journal.message << " " << journal.idNum << std::endl;
return 0;
}
我发现它适用于结构和类,无论它们是否有定义的构造函数。
显然默认构造函数在起作用,但由于以下几个原因,这让我感到困惑:
- 我以前从未见过这种语法(不足为奇,C++ 非常庞大)
- 它确实有效
- 无论是否定义了构造函数,都可以工作,因此可能是默认行为
我的问题是:
- 是否有此语法的名称和特定用途使其有别于常规的构造函数行为?如果有,为什么要使用(或不使用)它?
最佳答案
自从引入 C++11 以来,情况发生了变化,您可能应该阅读 list initialization
int x (0); // Constructor initialization
int x {0}; // Uniform initialization
在引入之前,您有各种初始化情况:
- 对象通过调用通常的 () 构造函数(如果没有参数,请注意 most vexing parse)
- 使用 {} 聚合类或数组
- 没有大括号的默认构造
现在您可以在所有这些中使用统一初始化。
需要注意的是,这两者并不是真正可以互换的,因为
std::vector<int> v (100); // 100 elements
std::vector<int> v {100}; // one element of value 100
你必须注意一个事实,如果类型有一个 initializer list constructor , 它将优先于重载决议。
也就是说,统一初始化可以是quite handy并且安全(防止缩小转换)。
关于C++ 这个很少使用的构造函数语法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40311618/