01/10/2018, 12:11
Nạp chồng toán tử
mình thắc mắc là sao mình code như này thì báo lỗi:
Cphanso kq;
kq=a+b;
nhưng như này thì code lại chạy đúng:
Cphanso kq=a+b;
Cphanso là class phân số mình định nghĩa và thiết lập phương thức khởi tạo rồi, định nghĩa cả operator+:
#include <iostream>
using namespace std;
class Cphanso
{
private:
int tu;
int mau;
public:
Cphanso();
Cphanso(int, int);
Cphanso(const Cphanso&x);
~Cphanso();
Cphanso operator=(Cphanso &);
Cphanso operator+(Cphanso);
friend istream& operator >>(istream &is,Cphanso &x);
friend ostream& operator <<(ostream &os,Cphanso &x);
};
Cphanso Cphanso::operator+(Cphanso x)
{
Cphanso temp;
temp.tu=tu*x.mau+mau*x.tu;
temp.mau=mau*x.mau;
return temp;
}
Cphanso Cphanso::operator=(Cphanso &x)
{
tu=x.tu;
mau=x.mau;
return *this;
}
Cphanso::~Cphanso()
{
return;
}
Cphanso::Cphanso()
{
tu=0;
mau=1;
}
Cphanso::Cphanso(const Cphanso&x)
{
tu=x.tu;
mau=x.mau;
}
Cphanso::Cphanso(int t, int m)
{
tu=t;
mau=m;
}
istream& operator >>(istream &is,Cphanso &x)
{
cout<<"Nhap tu";
is>>x.tu;
cout<<"Nhap mau";
is>>x.mau;
return is;
}
ostream& operator <<(ostream &os,Cphanso &x)
{
os<<x.tu<<"/"<<x.mau<<endl;
return os;
}
int main()
{
Cphanso a,b;
cin>>a>>b;
Cphanso kq;
kq=(a+b);
cout<<kq;
return 0;
}
Bài liên quan
Hi phu tran.
Khi
Cphanso kq; kq=a+b;
gọi hàm sao chép (operator=).còn
Cphanso kq=a+b;
gọi hàm tạo sao chép Cphanso(const Cphanso&x);.Bạn xem lại hàm bị lỗi xem.