When creating objects in C ++ and the difference between the parentheses without brackets (rpm)

c ++ to create an object syntax -----

1 Create MyClass a on the stack;

2 created on the heap brackets MyClass * a = new MyClass ();

3 without the brackets MyClass * a = new MyClass;

4 .--------------- MyClass a (); declares a return value of a function of no arguments MyClass type.

 1 #include <iostream>
 2 class MyClass
 3 {
 4 public:
 5     MyClass() 
 6     { 
 7         std::cout << "Hello MyClass!" << std::endl; 
 8     }
 9     MyClass(int i):num(i)
10     {
11         std::cout << "Hello MyClass!------int" << std::endl; 
12     }
13  
14     void MyMethod() 
15     { 
16          STD :: COUT << " output membership NUM: " << << NUM STD :: endl; 
 . 17      }
 18 is   
. 19  Private :
 20 is      int NUM;
 21 is  };
 22 is  int main ()
 23 is  {
 24      // ---- ----------- call the constructor for 
25      MyClass C1; // indication constructor with no arguments, or parameters have default constructor. 
26 is      MyClass C2 (); // not called no-argument constructor, in each case there is a declaration of a function returns a value of type MyClass only 
27      MyClass C3 ( . 1 ); // call the constructor parameter int 
28      / *--------------- For new keywords in brackets and the difference is not bracketed ---
 29      1. For custom types, there is no difference, are using the default constructor
 30      2 for the built-in type is initialized brackets
 31 is      * / 
32      STD :: COUT << STD :: endl;
 33 is      MyClass * C4 = new new MyClass ();
 34 is      c4- at the> MyMethod ();
 35      MyClass * = C5 new new MyClass ( . 1 );
 36      C5-> MyMethod ();
 37 [      MyClass = C6 * new new MyClass;
 38 is      C6-> MyMethod ();
 39   
40      // built-in type 
41 is      STD :: << COUTstd::endl;
42     int *pint1 = new int(1);
43     int *pint2 = new int();
44     int *pint3 = new int;
45  
46     std::cout<<*pint1<<" "<<*pint2<<" "<<*pint3<<std::endl;
47     return 0;
48 }

Output:

 

 

Conclusion: For built-in types when creating new objects Keywords: brackets will be initialized, without parentheses is not initialized; for custom types will call the default constructor, plus without brackets no difference.

 

Guess you like

Origin www.cnblogs.com/Stephen-Qin/p/11619897.html