初级 C++ 程序员常犯的一个错误是,采用以下方式声明一个用默认构造函数初始化的对象:
// oops! declares a function, not an object
Sales_item myobj();
The declaration of myobj compiles without complaint. However, when we try to use myobj
编译 myobj 的声明没有问题。然而,当我们试图使用 myobj 时
Sales_item myobj(); // ok: but defines a function, not an object if (myobj.same_isbn(Primer_3rd_ed)) // error: myobj is a function
the compiler complains that we cannot apply member access notation to a function! The problem is that our definition of myobj is interpreted by the compiler as a declaration of a function taking no parameters and returning an object of type Sales_itemhardly what we intended! The correct way to define an object using the default constructor is to leave off the trailing, empty parentheses:
编译器会指出不能将成员访问符号用于一个函数!问题在于 myobj 的定义被编译器解释为一个函数的声明,该函数不接受参数并返回一个 Sales_item 类型的对象——与我们的意图大相径庭!使用默认构造函数定义一个对象的正确方式是去掉最后的空括号:
// ok: defines a class object ...
Sales_item myobj;
On the other hand, this code is fine:
另一方面,下面这段代码也是正确的:
// ok: create an unnamed, empty Sales_itemand use to initialize myobj Sales_item myobj = Sales_item();
Here we create and value-initialize a Sales_item object and to use it to initialize myobj. The compiler value-initializes a Sales_item by running its default constructor.
在这里,我们创建并初始化一个 Sales_item 对象,然后用它来按值初始化 myobj。编译器通过运行 Sales_item 的默认构造函数来按值初始化一个 Sales_item。