//当重载了转换运算符后,宜用explicit 标明显式转换要求
class A;
class B;
class A
{
public:
A(){}
explicit A(B& other)
{ //B转换成A
printf("A: B to A\n");
}
};
class B
{
public:
B(){ printf("B\n");}
operator A()
{ //B转换成A
printf("operator: B to A\n");
return A();
}
};
void testTo(A a)
{
}
void main()
{
B b;
A a1 = b; //未explicit时有岐义,但编译器未提示,并默认用构造函数来转换
testTo(b);//未explicit时有岐义, 编译器能识别, 任选构造或操作符之一去掉其功能也可消除岐义
system("pause");
}
//---------------------------------------------
#include <iostream>
using namespace std;
class A
{
public:
A(int n):m_n(n){ printf("A\n");}
~A(){ printf("~A\n"); }
int m_n;
};
class B
{
public:
explicit B(int n):m_n(n),bCopy(false)
{
printf("B\n");
}
B(B& b):m_n(b.m_n),bCopy(true)
{//拷贝构造函数
printf("copy B\n");
}
~B()
{
if( bCopy) printf("copy ~B\n");
else printf("~B\n");
}
int m_n;
private:
bool bCopy;
};
void testA(A a)
{
}
void testB(B b)
{
}
void test()
{
A a = 3;//隐式转换
testA(3);
//B b = 3; 隐式转换,error
//testB(3); error
B b(3);//显式转换
testB( b);
}
void main()
{
test();
system("pause");
}
//--------------------------------------------
发现一个匿名对象的问题
上方test函数里如果是以下这样调用:
testB( B(3));
那么会发现类的构造函数没被调用。
莫非匿名对象不会调用类的构造函数? 而且有无实现拷贝构造函数也会影响匿名对象的构造和析构情况? 不明。。。
匿名对象还可以这样用:
const2buffer b = const2buffer(pTest);