转换类型操作符
- 必须是成员函数
- 不能是指定返回类型
- 形参表必须是空
- 必须显示的返回一个指定类型的值
- 不应该改变被转换对象,通常定义为const
#include <iostream>
#include <string>
using namespace std;
class Dog
{
public:
Dog(string n, int a, double w):name(n),age(a),weight(w){}
// 转换操作符
// 必须是成员函数
// 不能是指定返回类型
// 形参表必须是空的
// 必须显示的返回一个指定类型的值
// 不应该改变被转换对象,通常定义为const
operator int() const
{
return age;
}
operator double() const
{
return weight;
}
private:
int age;
double weight;
string name;
};
int main()
{
int a, b;
double c;
a = 10;
b = a;
Dog d("bill", 6, 15.1);
b = d;
c = d;
cout << b << endl;
cout << c << endl;
return 0;
}