cc24a_c++_转换函数operator int

c++ cc24a_demo //转换函数,用来做转换操作符,int()括号里面必须是空的,必须定义为const,代码示范

#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//转换函数,用来做转化操作符,int()括号里面必须是空的,必须定义为const
    {
        return age;
    }
    operator double() const//转换函数
    {
        return weight;
    }
    operator std::string() const//转换函数
    {
        return name;
    }
private:
    int age;
    double weight;
    string name;
};

int main()
{
    int a, b;
    a = 10;
    b = a;
    Dog d("Bill",6,15.0);
    b = d; //d得到的是整形,调用转换函数,operator int()
    cout << b << endl;

    getchar();
    return 0;
}
发布了469 篇原创文章 · 获赞 211 · 访问量 95万+

猜你喜欢

转载自blog.csdn.net/txwtech/article/details/104434885
今日推荐