如何在 C++ 中为变量正确设置 declare/assign 值
How to correctly declare/assign values for variables in c++
我是否应该在我的 C++ 程序的顶部声明变量,然后再赋值:
int i;
std::string x;
std::string retval;
x = "foo";
i = 5;
retval = somefunction();
或者 correct/acceptable 以下列方式为变量赋值:
int i = 5;
std::string x = "foo";
std::string retval = somefunction();
我是c++的新手,我想知道c++社区接受哪种方式。
当你事先知道初始值时,第二种方法更有效,因为你只调用构造函数,而第一种方法是先调用默认构造函数,然后调用赋值运算符。
第二种方式更符合 C++ 的习惯,应该是首选。
另见核心指南 NR.1:
Reason
The “all declarations on top” rule is a legacy of old programming languages that didn’t allow initialization of variables and constants after a statement. This leads to longer programs and more errors caused by uninitialized and wrongly initialized variables.
它也更有效率,因为第一个是默认构造,然后是赋值,第二个是简单构造。
我是否应该在我的 C++ 程序的顶部声明变量,然后再赋值:
int i;
std::string x;
std::string retval;
x = "foo";
i = 5;
retval = somefunction();
或者 correct/acceptable 以下列方式为变量赋值:
int i = 5;
std::string x = "foo";
std::string retval = somefunction();
我是c++的新手,我想知道c++社区接受哪种方式。
当你事先知道初始值时,第二种方法更有效,因为你只调用构造函数,而第一种方法是先调用默认构造函数,然后调用赋值运算符。
第二种方式更符合 C++ 的习惯,应该是首选。 另见核心指南 NR.1:
Reason
The “all declarations on top” rule is a legacy of old programming languages that didn’t allow initialization of variables and constants after a statement. This leads to longer programs and more errors caused by uninitialized and wrongly initialized variables.
它也更有效率,因为第一个是默认构造,然后是赋值,第二个是简单构造。