理解类型转换 1

#include "stdafx.h"
#include <windows.h>
#include <iostream>
#include <string>

/*
C++可以定义如何讲其它 类型的对象隐式转为我们的类类型,或者将我们的类类型对象转为其它类型。
1 类型A的对象 ->(隐式) 类类型B, 用例子简单理解就是 char* -> std::string
2 类类型A的对象 ->(隐式) 类型B, 用例子简单理解就是 CSmallInt -> int

怎么做到1? 可以用单个参数调用的构造函数定义了从形参类型到该类类型的一个隐式转换。
关键字: 单个参数 -> 调用构造函数 -> 形参类型 -> 类类型

怎么做到2?可以定义转换操作符,给给定的类类型的对象,该操作符将产生其它类型的对象.
*/

namespace ns_objecttype_test
{
//
//CFruit,作为类型A的对象 ->(隐式) 类类型B的例子
//
class CFruit
{
public:
explicit CFruit(std::string name, std::string Color = "red"):
m_name(name),
m_Color(Color)
{

}
bool isSameTypeFruit(const CFruit& Fruit) const
{
return (m_name == Fruit.m_name);
}

private:
std::string m_name;
std::string m_Color;
};

//
//
//
class CSmallInt
{
public:
CSmallInt(int i = 0): m_var(i)
{
if( i > 256 || i < 0)
{
throw std::out_of_range("Bad CSmallInt init");
}
}

/*
转换函数采用 operator type()写法.
*/

operator int() const
{
return m_var; //std::cout << si + 10 << std::endl;
}
private:
int m_var;

};

class CSmallInt2
{
public:
CSmallInt2(int i = 0): m_var(i)
{
if( i > 256 || i < 0)
{
throw std::out_of_range("Bad CSmallInt init");
}
}
int GetVar()
{
return m_var;
}
private:
int m_var;

};

int operator+(CSmallInt2& si1, int si2)
{
return si1.GetVar() + si2;
}
}

void test_ns_objecttype_test()
{
ns_objecttype_test::CFruit Orange("Orange");
ns_objecttype_test::CFruit Orange2("Orange");
ns_objecttype_test::CFruit apple("apple");

//加上explicit后就编译不通过了.
//std::cout << Orange.isSameTypeFruit(std::string("Orange")) << std::endl;

//
//需要这么调用.
//
std::cout << Orange.isSameTypeFruit(Orange2) << std::endl;

//Orange.isSameTypeFruit(std::string("Orange")),
//系统先生成一个临时CFruit对象,并且以std::string("Orange")作为形参调用临时CFruit对象的构造函数
//

/*
一般只将有单个参数(去掉默认值参数个数)的constructor声明为explicit,而copy constructor不要声明为explicit.
*/

// ----------------------------------------------
ns_objecttype_test::CSmallInt2 si2 = 10;

std::cout << si2 + 10 << std::endl; //这里通过操作符重载,si2 + 10返回一个int值,但如果si2 > 10呢,还得再重载operator>

//也可以用operator type()来做转换.
ns_objecttype_test::CSmallInt si = 10;

std::cout << si + 10 << std::endl;
std::cout << (si > 9) << std::endl; //这样只要存在转换,编译器就会使用内置转换的地方调用operator type()转换函数.
std::cout << si << std::endl;


}