Initialize and initialize while creating class objects

Asked 2 weeks ago, Updated 2 weeks ago, 1 views

#include <iostream>
using namespace std;

class CTest
        m_Value = 0;

    CTest(const CTest& obj)
        m_Value = 2;

    int m_Value;

void main()
    CTest t;
    t.m_Value = 1;

    CTest t1(t);
    CTest t2 = t;
    CTest t3; t3 = t;

    cout << "t1: " << t1.m_Value << endl;
    cout << "t2: " << t2.m_Value << endl;
    cout << "t3: " << t3.m_Value << endl;

There's a code. If you do CTest t; in the main function, call the constructor and t.m_Value = 0; Put 1 in t.m_Value and t.The m_value is 1 It is understandable that t1 takes the member data value as it is through the copy generator below.

I think the reason why there is a difference between t2 and t3 is whether or not an object is initialized when it is created It looks like a difference, but it's a little confusing. t2 is the substitution as the object is created, so it goes into the copy generator Since t3 is substituted after the object is created, is it just treated as a copy-to-put operator?


2022-09-20 11:38

1 Answers

CTest t1(t);
CTest t1=t;
CTest t1{t};

The three above are the same thing.

If you want CTest1=t; to stop working, you can explicitly put the exploit keyword in front of the constructor as shown below.

explicit CTest(const CTest& obj)

explicit and then compile it. Then CTest1=t; will cause an error.

2022-09-20 11:38

If you have any answers or tips

© 2022 pinfo. All rights reserved.