#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;
}
![]() |