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(); 
 
}
结果:


这样,我们就可以对不是同一条继承链上的类进行转换了!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值