转换操作符 和转换函数

来源:互联网 发布:淘宝极有家优质网店 编辑:程序博客网 时间:2024/05/16 00:29
#include <iostream>#include <string>using namespace std;class Dog{public:Dog(string n, int a, double w):name(n),age(a),weight(w){}operator int() const  // 转换函数,{return age;}operator double() const  // 转换函数,{return weight;}private:string name;int age;double weight;};int main(){int a, b;a = 8;b = a;Dog c("cui",25,50.11);b = c;cout << b << endl;  // 输出的是25,只是将对应的int型转才能换成。转换操作符不能指定返回类型,形参表必须是空的,//必须显示地返回一个指定类型的值,不应该改变被转换的对象,通常定义为const, double d;d = c;cout << d << endl;return 0;}

0 0