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


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

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

posted @ 2015-10-23 13:20  zfyouxi  阅读(133)  评论(0编辑  收藏  举报