在运算符重载中引用

Referencing in Operator Overloading

提问人:Rituraj Dutta 提问时间:7/21/2020 最后编辑:cigienRituraj Dutta 更新时间:7/21/2020 访问量:29

问:

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

#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;
        }

如果我写而不是 ,则 OUTPUT 将更改为: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

有人可以解释一下这两种情况下发生了什么吗? 是的,还有一件事要注意的是,在成员函数中,有什么用,我试图删除它并且 OUTPUT 不受影响??const Test &operator=const

C++ operator-重载 复制构造函数

评论


答:

1赞 Oleh 7/21/2020 #1

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