C 常数参考返回算法=作为非函数的声明

c++ constant reference return declaration of operator = as non function

本文关键字:函数 声明 常数 参考 返回 算法      更新时间:2023-10-16

请告诉我在下面的该代码中做错了什么,编译器给我带来了错误1.运算符声明=作为非功能2. const之前的预期主要表达我无法识别我的错误

等等请帮助我

#include <iostream>
using namespace std;

class myClass{
    int a;
    int b;
    public:
        myClass();
        myClass(int x, int y);
        const myClass& operator=(const myClass &);  
        void display();     
};

myClass::myClass(){
    a=0;
    b=0;
}
myClass::myClass(int x, int y){
    this->a=x;
    this->b=y;
}
const myClass& myClass::operator=(const class & rightobj){
    if(this!=&rightobj){
        this->a=rightobj.a;
        this->b=rightobj.b;
    }
    return *this;
}
void myClass::display(){
    cout<<a<<endl;
    cout<<b<<endl;
}
int main(){
myClass class1(2,3);
myClass class2;
class2=class1;
class2.display();

return 0;
}

在这里您有一个错字:

const myClass& myClass::operator=(const class & rightobj)
                                       //^^Should be myClass