C++ 运算符用指针重载
C++ operator overloading with pointers
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;
}
为什么这不起作用并给出:
3 IntelliSense: nonmember operator requires a parameter with class or enum type
显然,operator+ 要求第一个参数不是指针。
这会起作用:
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;
}
但是如果你不 return 指针会更安全,就像 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;
}
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;
}
为什么这不起作用并给出:
3 IntelliSense: nonmember operator requires a parameter with class or enum type
显然,operator+ 要求第一个参数不是指针。 这会起作用:
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;
}
但是如果你不 return 指针会更安全,就像 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;
}