shu*_*jan 4 c++ operator-overloading visual-c++
#include<iostream>
using namespace std;
class test
{
int a, b;
public:
test() {
a=4; b=5;
}
test(int i,int j=0) {
a=i; b=j;
}
test operator +(test c) {
test temp;
temp.a=a+c.a;
temp.b=b+c.b;
return temp;
}
void print() {
cout << a << b;
}
};
int main() {
test t1, t2(2,3), t3;
t3 = t1+2;
t3.print();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
编译器如何能接受像一份声明t3=t1+2;
,其中2
没有一个对象?
编译器看到您正在调用operator+(test)
并尝试使用构造函数隐式转换2
为test
成功test(int i,int j=0)
.
如果要显式转换,则必须将构造函数更改为explicit test(int i, int j=0)
.在这种情况下,您的代码将生成编译器错误,因为2
无法隐式转换为test
.您需要将表达式更改为t1 + test(2)
.
归档时间: |
|
查看次数: |
96 次 |
最近记录: |