copy constructor example const

#include<iostream>
using namespace std;

class A
{
private:
    int value;

public:
    A(int n)
    {
        value = n;
    }

    A(A other)          ->改成      A(const A& other)  
    {
        value = other.value;
    }

    void Print()
    {
        cout << value << endl;
    }
};

int main()
{
    A a = 10;
    A b = a;
    b.Print();
    return 0;
}

In the above code, the parameter passed in by the copy constructor A(A other) is an instance of A. Since it is a pass-by-value parameter, we call the copy constructor when we copy the formal parameter to the actual parameter. Therefore, if the copy constructor is allowed to pass by value, the copy constructor will be called within the copy constructor, which will form an endless recursive call and cause a stack overflow. Therefore, the C++ standard does not allow copy constructors to pass value parameters, and in Visual Studio and GCC, it will compile errors. To solve this problem, we can change the constructor to A(const A& other), that is, change the value-by-value parameter to a constant reference.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325066009&siteId=291194637