C + + Primer Plus Sixth Edition notes
Thinking about Object declaration
Transferred from: http://www.cnblogs.com/weiqubo/archive/2009/11/02/1930042.html
What is the difference between the syntax for defining an object in C + + with parentheses and without parentheses?
- #include <iostream>
- Class MyClass
- {
- Public
- MyClass ()
- {
- Std::cout << "Hello myclass!" << Std::endl;
- }
- Public
- void MyMethod ()
- {
- Std::cout << "Hello mymethod!" << Std::endl;
- }
- };
If this defines the object: MyClass obj; Then its constructor will be executed if obj is called. MyMethod (); it will execute correctly.
However, if you have parentheses: MyClass obj (); Then its constructor will not be executed, calling obj. MyMethod (); Syntax errors also occur, what is the syntax for defining obj?
MyClass obj () defines obj as a syntax that defines a parameterless function named obj with the type MyClass class (that is, the return value is MyClass type).
In addition, if the dynamic heap allocation is to be parenthesized, such as MyClass *obj = new MyClass () will not error (but, in the vc6.0 does not add () No error, and the result is the same, the reason to be solved? However, if a constructor with parameters is defined in the class, it is definitely wrong to define the class without parentheses #add to avoid errors, uniform parentheses are good)
C + + Primer Plus Sixth Edition notes