类中定义常量的方式:
- 枚举
enum{x=10}; //版本1
- 使用static
static const int y=10; //版本2
先来看一个简单的类的定义:
class test
{
public:
test(double);
//explicit test(double);//关闭隐式转换
operator int() const;
void show();
private:
enum{x=10}; //版本1
static const int y=10; //版本2
int a;
double b;
double c;
};
接受一个参数的构造函数才能作为转换函数,看构造函数的定义,函数体中分别测试两种定义常量的方式:
test::test(double t) //接受一个参数的构造函数才能作为转换函数
{
a=int(t)/x; //x=10;
b=int(t)%y; //y=10;
c=t;
}
创建转换函数:operator typename();
转换函数要注意的地方:
- 必须是类方法
- 不能指定返回类型
- 不能有参数
这里创建了一个转换为int类型的转换函数:
test::operator int() const //创建转换函数
{
return int(c+0.5);
}
show()函数将私有成员的值打印:
void test::show()
{
cout<<"a="<<a<<endl;
cout<<"b="<<b<<endl;
cout<<"c="<<c<<endl;
}
下面来测试数据,将285.7传给构造函数,查看a,b,c的值:
test q(285.7);
q.show();
类型转换的测试(显示转换),这里有两个版本:
test p(2.8);
//版本1
int x=p;
cout<<"版本1:int(2.8+0.5)="<<x<<endl;
//版本2
cout<<"版本2:int(2.8+0.5)="<<int(p)<<endl;
若要关闭隐式转换,在构造函数声明中:
explicit test(double);//关闭隐式转换
测试隐式转换,此时不会报错:
//测试隐式转换
test imp=2.8;
cout<<int(imp)<<endl;
取消类中的关闭隐式转换的屏蔽,屏蔽构造函数声明:
//test(double);
explicit test(double);//关闭隐式转换
这时就会发现测试隐式转换的程序报错,隐式转换已经关闭!