#include <iostream>
using namespace std;
class AnotherPoint
{
private:
double _ax;
double _ay;
public:
//explicit
AnotherPoint(double x=0,double y=0):_ax(x),_ay(y)
{
cout<<"AnotherPoint(int,int)"<<endl;
}
friend std::ostream & operator << (std::ostream & os,const AnotherPoint &rhs);
friend class Point;
};
std::ostream & operator << (std::ostream & os,const AnotherPoint & rhs)
{
os<<"("<<rhs._ax<<","<<rhs._ay<<")";
return os;
}
class Point
{
private:
int _x;
int _y;
public:
//explicit
Point(int x=0,int y=0):_x(x),_y(y)
{
cout<<"Point(int,int)"<<endl;
}
//explicit
Point(AnotherPoint & a):_x(a._ax),_y(a._ay)
{
cout<<"Point(AnotherPoint & a)"<<endl;
}
//point& operator=(const anotherPoint& rhs);
// 賦值運算符只能兩個相同類型的類對象之間
friend std::ostream & operator << (std::ostream & os,const Point & rhs);
};
std::ostream & operator << (std::ostream & os,const Point & rhs)
{
os<<"("<<rhs._x<<","<<rhs._y<<")";
return os;
}
|
//由其它類型向自定義類型進行轉換,都是經過構造函數來完成的
//隱式轉換
//explicit能夠禁止隱式轉換
int main(void)
{
Point p1;
cout<<5<<"轉換成:";
p1=5;
//類型不一樣,因此構造函數轉換
//若是有operator=這就就報錯了
cout<<" p1 = "<<p1<<endl<<endl;
double d1=1.5;
cout<<d1<<"轉換成:";
p1=d1;
cout<<" p1 = "<<p1<<endl<<endl;
AnotherPoint p2(12.34,56.78);
cout<<" p2 = "<<p2<<endl;
cout<<"將p2轉換成p1"<<endl;
p1=p2;
//兩個都是類類型,因此直接賦值構造函數
cout<<" p1 = "<<p1<<endl<<endl;
return 0;
}
![]() |
#include <iostream>
using namespace std;
class AnotherPoint
{
private:
double _ax;
double _ay;
public:
AnotherPoint(double x=0,double y=0):_ax(x),_ay(y)
{
cout<<"AnotherPoint(double,double)"<<endl;
}
friend ostream & operator << (ostream & os,const AnotherPoint & rhs);
};
class Point
{
private:
int _x;
int _y;
public:
Point(int x=0,int y=0):_x(x),_y(y)
{
cout<<"Point(int,int)"<<endl;
}
//類型轉換函數
operator int()
{
return _x;
}
operator double()
{
return _x*_y;
}
operator AnotherPoint()
{
return AnotherPoint(_x,_y);
// 這裏直接返回類類型對象,因此不能單單AnotherPoint類前向聲明,必須給出完整定義
}
friend ostream & operator << (ostream &os,const Point & rhs);
};
|
ostream& operator << (ostream& os,const AnotherPoint & rhs)
{
os<<"("<<rhs._ax<<","<<rhs._ay<<")";
return os;
}
ostream& operator << (ostream& os,const Point & rhs)
{
os<<"("<<rhs._x<<","<<rhs._y<<")";
return os;
}
int main()
{
Point p(4,5);
int x=p;
cout<<"x = "<<x<<endl;
double y=p;
cout<<"y = "<<y<<endl;
AnotherPoint p1;
cout<<"p1 = "<<p1<<endl;
p1=p;
cout<<"p1 = "<<p1<<endl;
return 0;
}
![]() |