Copy Constructor and Copy Assignment in C++

There is a lot of syntax inconsistencies in C++, which makes C++ harder for
people to understand. For example, = sometimes denotes copy assignment. 
Sometimes it denotes copy construction.

#include <iostream>
using namespace std;

class Thing {
  public:
    Thing() {
      cout << "Thing constructor\n";
    }
    Thing(const Thing& other) {
      cout << "Thing copy constructor\n";
    }
    Thing& operator = (const Thing& other) {
      cout << "Thing copy assignment\n";
    }
};

int main(int argc, const char *argv[]) {
  Thing t1; // constructor
  Thing t2 = t1; // copy constructor (initialization by copy)
  Thing t3(t1); // copy constructor
  t3 = t1; // copy assignment
  return 0;
}
 

 

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