Sae*_*yth -1 c++ operator-overloading
struct Test {
int A = 0;
int B = 0;
};
Test* operator+(const Test *x, const Test *r) {
Test *test = new Test;
test->A = x->A + r->A;
test->B = x->B + r->B;
return test;
}
Run Code Online (Sandbox Code Playgroud)
为什么这不会工作并给予:
3 IntelliSense:非成员运算符需要具有类或枚举类型的参数
显然,运算符+请求第一个参数不是指针.这可行:
Test* operator+(const Test &x, const Test& r){
Test *test = new Test;
test->A = x.A + r.A;
test->B = x.B + r.B;
return test;
}
Run Code Online (Sandbox Code Playgroud)
但是如果你没有返回指针就更安全,就像Jonachim说的那样.你应该做这个:
Test operator+(const Test &x, const Test& r){
Test test;
test.A = x.A + r.A;
test.B = x.B + r.B;
return test;
}
Run Code Online (Sandbox Code Playgroud)