小类型初始化给大类型是合法的
#include <iostream>
#include <string>
using namespace std;
int main()
{
short s = 'a';
unsigned int ui = 1000;
int i = -2000;
double d = i;
cout << "d = " << d << endl;
cout << "ui = " << ui << endl;
cout << "ui + i = " << ui + i << endl;
//u+i编译器默认进行隐式转换
//i从int转换为unsigned int
//编译器默认会把变量从小字节转换成大字节
if( (ui + i) > 0 )
{
cout << "Positive" << endl;
}
else
{
cout << "Negative" << endl;
}
//s+'b' 两者都会隐式转换为int类型
cout << "sizeof(s + 'b') = " << sizeof(s + 'b') << endl;
return 0;
}
编译器的隐式转换,22行就等价于:t=Test(5);
编译可以通过
ClassName(value): 手工调用构造函数
#include <iostream>
#include <string>
using namespace std;
class Test
{
int mValue;
public:
Test()
{
mValue = 0;
}
//被explicit修饰,该转换构造函数只能进行显示转换
explicit Test(int i)
{
mValue = i;
}
Test operator + (const Test& p)
{
Test ret(mValue + p.mValue);
return ret;
}
int value()
{
return mValue;
}
};
int main()
{
Test t;
t = static_cast<Test>(5); // t = Test(5);
Test r;
r = t + static_cast<Test>(10); // r = t + Test(10);
cout << r.value() << endl;
return 0;
}
输出:15
小结1
问题:
可以,引入新的语法规则
#include <iostream>
#include <string>
using namespace std;
class Test
{
int mValue;
public:
Test(int i = 0)
{
mValue = i;
}
int value()
{
return mValue;
}
operator int ()
{
return mValue;
}
};
int main()
{
Test t(100);
//一般写成:int i = t;(隐式类型转换)
int i = t.operator int();
cout << "t.value() = " << t.value() << endl;
cout << "i = " << i << endl;
return 0;
}
#include <iostream>
#include <string>
using namespace std;
class Test;
class Value
{
public:
Value()
{
}
explicit Value(Test& t)
{
}
};
class Test
{
int mValue;
public:
Test(int i = 0)
{
mValue = i;
}
int value()
{
return mValue;
}
operator Value()
{
Value ret;
cout << "operator Value()" << endl;
return ret;
}
};
int main()
{
Test t(100);
//由于Value中构造函数Value(Test& t)被explicit修饰
//所以不能进行隐式转换,下面的Value v=t;调用的是operator Value()
//如果将explicit去掉,编译会报错
//因为有两个函数可以进行隐式转换,编译器不知道选哪一个
Value v = t;
return 0;
}
改成中通常这么做:
杜绝了隐式转换带来的bug