#include<iostream>
//#include<stdio.h>
using namespace std;
class Test1{
public:
Test1(void){//无参构造 缺省构造
num = 0;
}
Test1(int n){
cout << "Test1::constructor" << endl;
num = n;
}
int & value(){
return num;
}
private:
int num;
};
class Test2{
public:
explicit Test2(int n){
cout << "Test2::constructor" << endl;
num = n;
}
int &value(){
return num;
}
private:
int num;
};
class Test3 {
public:
Test3(int n,int num111 = 0) {//这种情况也可能发生单参构造的类型转换
cout << "Test3::constructor" << endl;
num = n;
num1 = num111;
}
int &value() {
return num;
}
private:
int num;
int num1;
};
int main(){
Test1 t1;
cout << t1.value() << endl;
Test1 t2(100);
cout << t2.value() << endl;
t2 = 1000;//t2 = Test1(1000);隐式类型转换
cout << t2.value() << endl;
Test2 T2(100);
cout << T2.value() << endl;
//T2 = 1000;//error 二进制“=”: 没有找到接受“int”类型的右操作数的运算符(或没有可接受的转换)
T2 = Test2(1000);//只能显式的转换
cout << T2.value() << endl;
Test3 t3(100, 200);
t3 = 250;
cout << t3.value() << endl;
getchar();
return 0;
}
#include<iostream>
using namespace std;
class Pointer2D
{
public:
Pointer2D(int x,int y):m_x(x),m_y(y){}
private:
int m_x;
int m_y;
friend class Pointer3D;
friend ostream & operator<<(ostream&os,Pointer2D const &p2);
};
class Pointer3D
{
public:
Pointer3D(int x,int y,int z):m_x(x),m_y(y),m_z(z){}
//在目标类型中定义从源类型的类型转换构造函数(拷贝构造)
Pointer3D(Pointer2D const &p2):m_x(p2.m_x),m_y(p2.m_y),m_z(0)
{
cout<<"Pointer3D(Pointer2D const &p2)"<<endl;
}//p3 = p2
//在源类型中定义到目标类型的类型转换运算符函数
operator Pointer2D(void)const
{
cout<<"perator Pointer2D(void)const"<<endl;
return Pointer2D(m_x,m_y);//
}
friend ostream & operator<<(ostream&os,Pointer3D const &p3);
private:
int m_x;
int m_y;
int m_z;
};
ostream & operator<<(ostream&os,Pointer3D const &p3)
{
return os<<p3.m_x<<" "<<p3.m_y<<" "<<p3.m_z<<endl;
}
ostream & operator<<(ostream&os,Pointer2D const &p2)
{
return os<<p2.m_x<<" "<<p2.m_y<<endl;
}
class Integer
{
public:
Integer(int i = 0):m_i(i){}
operator int (void)const{
return m_i;
}
private:
int m_i;
};
int main(){
Pointer2D p2(1,2);
cout<<p2<<endl;
Pointer3D p3(4,5,6);
cout<<p3<<endl;
Pointer3D p31 = p2;//Pointer3D(Pointer2D const &p2)
cout<<p31<<endl;
p2 = p3;//p3.operator Pointer2D()
//cout<<p2<<endl;//4 5
getchar();
return 0;
}