question about copy constructor

后端 未结 3 1312
伪装坚强ぢ
伪装坚强ぢ 2021-01-20 10:08

I have this class:

class A {
private:
 int player;
public:
 A(int initPlayer = 0);
 A(const A&);
 A& operator=(const A&);
 ~A();
 void foo() cons         


        
相关标签:
3条回答
  • 2021-01-20 11:04

    When you call new A(a2);

    It will call one of the constructors.
    Which one it calls will depend on the type of a2.

    If a2 is an int then the default constructor is called.

    A::A(int initPlayer = 0);
    

    If a2 is an object of type A then the copy constructor will be called.

    A::A(const A&);
    
    0 讨论(0)
  • 2021-01-20 11:09

    Assuming a2 is an instance of A, this calls the copy constructor.

    It will call operator new to get dynamic memory for the object, then it will copy-construct a new object into the memory, then return a pointer to that memory.

    0 讨论(0)
  • 2021-01-20 11:11

    This depends on the data type of a2. If it is int or a type that can implicitly be converted to int, the default c'tor (A(int player=0)) will be called, if a2 is an instance of A or an type that can implicitly be converted to A (i.e. instance of a sub-class) the copy c'tor will be called.

    0 讨论(0)
提交回复
热议问题