首页 > 编程语言 > 详细

C++中Operator的使用(类型强制转换成员函数)

时间:2016-07-20 22:40:56      阅读:219      评论:0      收藏:0      [点我收藏+]

本文引自:http://www.jb51.net/article/41333.htm

 

operator用于类型转换函数:

类型转换函数的特征:

1) 型转换函数定义在源类中; 
2) 须由 operator 修饰,函数名称是目标类型名或目标类名; 
3) 函数没有参数,没有返回值,但是有return 语句,在return语句中返回目标类型数据或调用目标类的构造函数。

对象向基本数据类型转换:

#include<iostream>
#include<string>
using namespace std;
class D{
public:
 D(double d):d_(d) {}
 operator int() const{
  std::cout<<"(int)d called!"<<std::endl;
  return static_cast<int>(d_);
 }
private:
 double d_;
};
int add(int a,int b){
 return a+b;
}
int main(){
 D d1=1.1;
 D d2=2.2;
 std::cout<<add(d1,d2)<<std::endl;
 system("pause");
 return 0;
}

 

C++中Operator的使用(类型强制转换成员函数)

原文:http://www.cnblogs.com/RockyZuo/p/5689821.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!