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


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

     1 #include <iostream>
     2 #include <string>
     3 using namespace std;
     4 
     5 class Dog
     6 {
     7 public:
     8     Dog(string n, int a, double w) :name(n), age(a), weight(w) {}
     9     operator int() const//转换函数,用来做转化操作符,int()括号里面必须是空的,必须定义为const
    10     {
    11         return age;
    12     }
    13     operator double() const//转换函数
    14     {
    15         return weight;
    16     }
    17     operator std::string() const//转换函数
    18     {
    19         return name;
    20     }
    21 private:
    22     int age;
    23     double weight;
    24     string name;
    25 };
    26 
    27 int main()
    28 {
    29     int a, b;
    30     a = 10;
    31     b = a;
    32     Dog d("Bill",6,15.0);
    33     b = d; //d得到的是整形,调用转换函数,operator int()
    34     cout << b << endl;
    35 
    36     getchar();
    37     return 0;
    38 }
    欢迎讨论,相互学习。 txwtech@163.com
  • 相关阅读:
    P4168 [Violet]蒲公英
    P3320 [SDOI2015]寻宝游戏
    P2487 [SDOI2011]拦截导弹
    P3338 [ZJOI2014]力(FFT)
    P1975 [国家集训队]排队
    P4103 [HEOI2014]大工程
    虚树小结
    LVS初步
    常见指针定义解读
    可epoll队列
  • 原文地址:https://www.cnblogs.com/txwtech/p/12115391.html
Copyright © 2020-2023  润新知