C++中匿名对象和隐式构造

匿名对象:没有变量名,没有被指针指向的对象,用完后马上调用析构
     
     class Person {
         public:
         Person(){
            cout << "Person()" << endl;
         }
         }
         Person (const Person &person){
            cout << "const Person " << endl;
         }
         ~Person(){
            cout << "~Person()" << endl;
         }
         void display(){
            cout << "display()" << endl;
         }
     
     
         void test1(Person person){
         }
         Person test2() {
         return Person();
         }
     };
     
     
     int main (){
         Person().display();
         getchar();
         return 0;
     }
隐式构造:C++中存在隐式构造的现象:某些情况下,会隐式调用单参数的构造函数.可以通过关键字explicit禁止掉隐式构造
     class Person {
         int m_age;
         public:
         Person():Person(0){
            cout << "Person()" << endl;
         }
         }
         Person(int age):m_age(age) {
            cout << "Person(int )" << endl;
         }
         Person (const Person &person){
            cout << "const Person " << endl;
         }
         ~Person(){
            cout << "~Person()" << endl;
         }
         void display(){
            cout << "display() - age is"<< this->m_age << endl;
         }
     
     
         void test1(Person person){
     
         }
         Person test2() {
            return Person();
         }
     };
     
     
     int main (){
         Person person(10);
         person = 20;// 这里是隐式调用了构造函数,相等于person = Person(20);
         Person.display();
         getchar();
         return 0;
     }

你可能感兴趣的:(C++)