zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    wc 统计程序
    读C#程序
    VS2013 单元测试
    android开发心得之知识的量变到质变
    大学第一篇博客
    团队作业七
    团队作业六
    团队作业五
    团队作业四
    团队作业三
  • 原文地址:https://www.cnblogs.com/txwtech/p/12115391.html
Copyright © 2011-2022 走看看