banner
cells

cells

为美好的世界献上 code

Q187

Q187#

#include <iostream>

class C {
public:
    C() {
        std::cout << "1";
    }

    C(const C &other) {
        std::cout << "2";
    }

    C &operator=(const C &other) {
        std::cout << "3";
        return *this;
    }
};

int main() {
    C c1;
    C c2 = c1;
}

Answer#

click to see answer 12

Explain#

On the first line, C c1;, the object c1 is default initialized, so the default constructor is called, printing 1.

On the second line, C c2 = c1;, the object c2 is copy initialized, so the copy constructor is called, printing 2. (Note that no assignment is taking place, even though there's a = involved.)

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.