C++最短惊叹法则
当对象的定义看起来像函数声明时,编译器会将其看成函数的声明,而不是对象的定义。
示例
有如下代码:
class Student {
public:
Student() {
cout << "Student默认构造" << endl;
}
Student(int age) :age_(age) {
cout << "Student有参构造" << endl;
}
private:
int age_;
};
void test12() {
Student s1; // 调用 Student默认构造
Student s2{}; // 调用 Student默认构造
Student s3(20); // 调用 Student有参构造
Student s4{ 20 }; // 调用 Student有参构造
Student s5(); // 不会调用任何构造,因为编译器将其看成函数的声明
}