ostream& operator<<(ostream& out,diem d)
{
out<<"("<<d.gethoanh()<<" ; "<<d.gettung()<<")";
return out;
}
//Chả hiểu sao overload dịch là quá tải nhỉ,đọc chả liên quan gì đến nghĩa của //nó.Mình thấy dịch là nạp chồng nghe còn đỡ hơn.
VD trong lớp Điểm đơn thuần thế này.
Mình muốn dùng quá tải (operator) để quá tải toán tử xuất << . Để có thể xuất thẳng một đối tượng ra mà không cần dùng hàm hiện thị nữa mà ko biết làm thế nào. Mọi người dúp nhá.PHP Code:#include <iostream.h>
#include <conio.h>
#include <math.h>
class diem
{
private:
float x;
float y;
public:
diem()
{
x=0;
y=0;
};
diem(float a,float b)
{
x=a;y=b;
};
void settung(float t);
float gettung();
void sethoanh(float h);
float gethoanh();
void setdiem(diem j);
float KC(diem k);
void show();
};
void diem::settung(float t)
{
x=t;
};
float diem::gettung()
{
return x;
};
void diem::sethoanh(float h)
{
y=h;
};
float diem::gethoanh()
{
return y;
};
void diem::setdiem(diem j)
{
x=j.x;
y=j.y;
};
float diem::KC(diem k)
{
return sqrt((x-k.x)*(x-k.x)+(y-k.y)*(y-k.y));
};
void diem::show()
{
cout<<"("<<x<<" ; "<<y<<")";
};
ostream& operator<<(ostream& out,diem d)
{
out<<"("<<d.gethoanh()<<" ; "<<d.gettung()<<")";
return out;
}
//Chả hiểu sao overload dịch là quá tải nhỉ,đọc chả liên quan gì đến nghĩa của //nó.Mình thấy dịch là nạp chồng nghe còn đỡ hơn.
Code:friend ostream& operator<<(ostream&,diem&); //prototype ostream& operator<<(ostream& cout,diem& d) //cai dat { cout<<"("<<d.gethoanh()<<" ; "<<d.gettung()<<")"; return cout; }
//prototype bạn phải khai báo trong Class gì đó
ví dụ ở đây là Class điểm
Đây là code sau khi đã sửa. Sau khi quá tải chúng ta có thể tha hồ cout<< đối tượng mà ko cần hàm hiện thịPHP Code:#include <iostream.h>
#include <conio.h>
#include <math.h>
class diem
{
private:
float x;
float y;
public:
diem()
{
x=0;
y=0;
};
diem(float a,float b)
{
x=a;y=b;
};
void settung(float t);
float gettung();
void sethoanh(float h);
float gethoanh();
void setdiem(diem j);
float KC(diem k);
friend ostream& operator<<(ostream&,diem&); //prototype
};
ostream& operator<<(ostream& cout,diem& d) //cai dat
{
cout<<"("<<d.gethoanh()<<" ; "<<d.gettung()<<")";
return cout;
}
void diem::settung(float t)
{
x=t;
};
float diem::gettung()
{
return x;
};
void diem::sethoanh(float h)
{
y=h;
};
float diem::gethoanh()
{
return y;
};
void diem::setdiem(diem j)
{
x=j.x;
y=j.y;
};
float diem::KC(diem k)
{
return sqrt((x-k.x)*(x-k.x)+(y-k.y)*(y-k.y));
};
VD
PHP Code:void main()
{
diem a;
float c,d;
cout<<"\tNhap vao tung do: ";
cin>>c;
a.settung(c);
cout<<"\tNhap vao hoang do: ";
cin>>d;
a.sethoanh(d);
cout<<a;
getch();
}
bạn có biết trong khai ostream& operator(ostream&,diem&)
tại sao ostream lại có dấu &