zoukankan      html  css  js  c++  java
  • C++学习笔记33 转换操作符

    有时候,我们要转换为类类型和类类型,同时,这两个类继承关系不存在,这时候我们就需要一些所谓的转换操作符运营商.
    一个简单的例子.类别A转换为int种类
    #include <iostream> 
    #include <string> 
    using namespace std; 
    class A{ 
    private: 
    int n; 
    string str; 
    public: 
    A(int m,string s):n(m),str(s){ 

    }; 
    int main(){ 
    A a(10,"hello"); 
    int m=a; 
    cout<<"m="<<m<<endl; 
    //string s=a; 
    //cout<<"s="<<s<<endl; 
     
    }
    编译结果


    可能你想将其强制转换.比如
    int m=(int)a;
    结果还是不行,由于编译器依旧不知道应该怎么转换.


    这时候,就须要转换运算符了.
    这个转换运算符的类型例如以下:
    operator int ()const{
    return n;
    }
    函数名为operator int ,这个函数是没有返回类型的,由于返回类型是通过运算符的名称确定的:int
    同一时候应声明为const,由于不会改动被调用的对象.
    整个程序例如以下:
    #include <iostream> 
    #include <string> 
    using namespace std; 
    class A{ 
    private: 
    int n; 
    string str; 
    public: 
    A(int m,string s):n(m),str(s){ 

    operator int ()const{ 
    return n; 

    operator string()const{ 
    return str; 

    }; 
    int main(){ 
    A a(10,"hello"); 
    int m=a; 
    cout<<"m="<<m<<endl; 
    string s=a; 
    cout<<"s="<<s<<endl; 
     
    }

    执行结果:


    类类型转换为基本类型是这样,相同,转换为其它类类型也是相同的道理.
    #include <iostream> 
    #include <string> 
    using namespace std; 
    class A{ 
    private: 
    int n; 
    string str; 
    public: 
    A(int m,string s):n(m),str(s){ 

    A(string s){ 
    str=s+" is called!"; 

    operator int ()const{ 
    return n; 

    operator string()const{ 
    return str; 

    void show()const{ 
    cout<<"str="<<str<<endl; 

    }; 
    class B{ 
    private: 
    string s; 
    public: 
    B(string str):s(str){ 

    operator A()const{ 
    return s; 



    }; 
    int main(){ 
     
    B b("this is b "); 
    A a=b; 
    a.show(); 
     
    }
    结果:


    这项,我们将不能够继承的类相同链上被转换!

    版权声明:本文博主原创文章,博客,未经同意不得转载。

  • 相关阅读:
    HDU_1285_拓扑排序(优先队列)
    HDU_1087_Super Jumping! Jumping! Jumping!_dp
    STL_优先队列_(转载)
    数据结构课程笔记_拓扑排序
    滋阴清火中药方 (推荐--自用)
    文件与文档内容搜索工具软件
    CrossUI SPA Builder ---- feathers API框架
    广州交警网上车管所
    BIM 相关资料
    WIN10 ISO 官方
  • 原文地址:https://www.cnblogs.com/zfyouxi/p/4904240.html
Copyright © 2011-2022 走看看