转换函数的问题
#include<iostream>using namespace std;
class tet
{
private:
double real;
double imag;
public:
friend tetoperator +(tet a,tet b);
// operator double(){return real;}
tet(double a=0,double b=51):real(a),imag(b){}
tet(double r){imag=0,real=r;}
friend ostream& operator <<(ostream& out,tet a)
{
out<<a.real<<" "<<a.imag<<endl;
}
};
tetoperator +(tet a,tet b)
{
return tet(a.real+b.real,a.imag+b.imag);
}
int main()
{
tet c1(2,5),c2(5,5),c3;
double a;
c3=5.1+c1;//在这里报错
cout<<c3;
return 0;
}//请问这段代码错在哪,转换函数不应该把5.1改变成一个类吗?
不太懂,不过你可以试试c3=c1+5.1;? 这你想多了,不可能办的到。你重载的加法是传入两个tet对象,把对应的属性相加。使用的时候就必须是两个tet对象相加。把实参的类型强转成跟形参一致,这种事情大概只有int转double,或者子类转父类才能实现。数字转成对象,过于魔幻 倒戈卸甲 发表于 2020-4-24 16:06
这你想多了,不可能办的到。你重载的加法是传入两个tet对象,把对应的属性相加。使用的时候就必须是两个tet ...
事实上我刚刚已经做到了
#include<iostream>
using namespace std;
class tet
{
private:
double real;
double imag;
public:
friend tetoperator +(tet a,tet b);
// operator double(){return real;}
tet(){}
tet(double a,double b):real(a),imag(b){}
tet(double r){real=r,imag=0;}
friend ostream& operator <<(ostream& out,tet a)
{
out<<a.real<<" "<<a.imag<<endl;
}
};
tetoperator +(tet a,tet b)
{
return tet(a.real+b.real,a.imag+b.imag);
}
int main()
{
tet c1(2,5),c2(5,5),c3;
double a;
c3=5.1+c1;
cout<<c3;
return 0;
} #include <iostream>
using namespace std;
class tet
{
private:
double real;
double imag;
public:
tet operator+(const tet &rhs) const {
return tet(this->real + rhs.real, this->imag + rhs.imag);
}
tet() {imag = 0, real = 51;}
tet(double a, double b): real(a), imag(b) {}
tet(double r) {imag = 0, real = r;}
friend tet operator+(const tet &lhs, const tet &rhs) {
return lhs.operator+(rhs);
}
friend ostream &operator<<(ostream &out, const tet &a)
{
out << a.real << " " << a.imag << endl;
return out;
}
};
int main()
{
tet c1(2, 5), c2(5, 5), c3;
double a;
c3 = 5.1 + c1;//在这里报了什么错? 看错误提示呀
cout << c3;
return 0;
}
320374616 发表于 2020-4-24 16:20
事实上我刚刚已经做到了
#include
using namespace std;
嗯,好吧我错了。没仔细读代码,这里你提供了传入一个参数的构造函数。
页:
[1]