From Section 12.4.3 of C ++ primer version 4
3. Use the default constructor
A common mistake for Junior C ++ programmers is to declare an object initialized with the default constructor in the following way:
// Oops! Declares a function, not an object
Sales_item myobj ();
There is no problem in compiling the declaration of myobj. However, when we try to use myobj
Sales_item myobj (); // OK: But defines a function, not a object
If (myobj. same_isbn (primer_3rd_ed) // error: myobj is a function
The compiler will point out that the member accessors cannot be used in a function! The problem is that the definition of myobj is interpreted by the compiler as a declaration of a function. This function does not accept the parameter and returns a sales_item object ------- which is quite different from our intent!
The correct way to use the default constructor to define an object is to remove the final empty brackets:
// OK! Difines A Class Object
Sales_item myobj; // call the constructor implicitly <plus 10.3.2>
On the other hand, the following code is correct:
// OK: Create an unnamed, empty sales_item and use to initialize myobj
Sales_item myobj = sales_item (); // call the constructor explicitly <plus 10.3.2>
Here, we create and initialize a sales_item object, and then use it to initialize myobj by value. The Compiler initializes a sales_item by running the default constructor of sales_item.
----------------------------------------------- Cute split line ------------------------------------------------------------
This cainiao has just encountered this problem. Fortunately, it has been explained in the book, otherwise it will be depressing. I really don't understand why the compiler interprets it as a function declaration, and it is in *. cpp.
Now that I know the answer, let's look at the source code of <functional> and use the template class and () to execute relevant functions. for example, if typename classa () is not declared as a function, the <functional> library does not work.
// OK: Create an unnamed, empty sales_item and use to initialize myobj
Here, we create and initialize a sales_item object and use it to initialize myobj by value.
In the above two statements, I agree that the operations performed by calling constructor and implicitly calling constructor are the same. it should not show that calling constructor is to create an object first, and then assign values to the named object ?????????.
<C ++ primer plus Fifth Edition> page 316 dispelled my doubts. It was originally related to the compiler.