运算符重载中的引用

Referencing in Operator Overloading

我是运算符重载概念的新手,我刚刚实现了一个使用 class 重载 赋值运算符 的程序。这是我实现的代码:

#include<iostream>

using namespace std;

class Test{
    private:
        int id;
        string name;
    public:
        Test():id(0),name(""){

        }
        Test(int id,string name):id(id),name(name){

        }
        
        
    
        void print(){
            cout<<id<<" : "<<name<<endl<<endl;
        }
        const Test &operator=(const Test &other){
            cout<<"Assignment Running"<<endl;
            id=other.id;
            name=other.name;
            return *this;
        }
        Test(const Test &other){
        cout<<"Copy Constructor Running"<<endl;
        id=other.id;
        name=other.name;
        }

};

int main(){
    Test test1(10,"Raj");
    cout<<"Test1 running\n";
    test1.print();


    Test test2;
    test2=test1;
    
   
    cout<<"Test2 running\n";
    test2.print();


    Test test3;
    test3.operator=(test2);                 //It's working as test2=test1
    
    cout<<"Test3 running\n";
    test3.print();

    Test test4=test1;
    cout<<"Test4 Running"<<endl;
    test4.print();

    return 0;
}

输出:

Test1 running
10 : Raj

Assignment Running
Test2 running
10 : Raj

Assignment Running
Test3 running
10 : Raj

Copy Constructor Running
Test4 Running
10 : Raj

在这个函数中:

 const Test &operator=(const Test &other){
            cout<<"Assignment Running"<<endl;
            id=other.id;
            name=other.name;
            return *this;
        }

如果我写 operator= 而不是 &operator=,输出将更改为:

Test1 running
10 : Raj

Assignment Running
Copy Constructor Running
Test2 running
10 : Raj

Assignment Running
Copy Constructor Running
Test3 running
10 : Raj

Copy Constructor Running
Test4 Running
10 : Raj

有人可以解释这两种情况下发生了什么吗?? Nd yeah 还有一点需要注意的是,在成员函数const Test &operator=中,const有什么用,我试过去掉它,OUTPUT不受影响??

简而言之,const Test &operator= 将通过引用授予对您的对象的访问权限。在第二种情况下,const Test operator= 将创建对象的副本并将此新对象分配给输出变量,这在大多数情况下是不必要的。它是通过复制构造函数完成的。 const 关键字将强制输出对象不可变,您将无法调用修改对象状态的方法(未在其名称中声明为 const)。