主要是想到了如果是用类的方法进行运算符重载
class Person
{
public:
Person(int n1, int n2) : m_A(n1),m_B(n2){};
Person PersonAddPerson(Person &p1);
int m_A;
int m_B;
};
Person operator+(Person& p1)
{
Person temp(0, 0);
temp.m_A = this->m_A + p1.m_A; //代码在this处报错,错误提示:【this只能用于非静态成员内部】
temp.m_B = this->m_B + p1.m_B;
return temp;
}
【this只能用于非静态成员内部】
无
我想要达到的效果是可以在类外使用作用域进行申明,不知道是否可行,希望能有带佬帮助
在类外定义类成员函数,首先必须在类中有函数声明,其次需要加上作用域
#include <iostream>
using namespace std;
class Person
{
public:
Person(int n1, int n2):m_A(n1),m_B(n2){};
Person operator+(Person& p1);//声明重载函数作为类成员函数
int m_A;
int m_B;
};
Person Person::operator+(Person& p1) //类外定义重载函数
{
Person temp(0,0);
temp.m_A = this->m_A + p1.m_A;
temp.m_B = this->m_B + p1.m_B;
return temp;
}
int main()
{
cout<<"Hello World";
Person p(1,1),p1(2,2);
return 0;
}
Person Person::operator+(Person& p1)
{
Person temp(0, 0);
temp.m_A = this->m_A + p1.m_A; //代码在this处报错,错误提示:【this只能用于非静态成员内部】
temp.m_B = this->m_B + p1.m_B;
return temp;
}