• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

浅谈C++类型转化(运算符重载函数)和基本运算符重载(自增自减)

c++ 搞代码 4年前 (2022-01-06) 40次浏览 已收录 0个评论

下面小编就为大家带来一篇浅谈C++类型转化(运算符重载函数)和基本运算符重载(自增自减)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧

类型转化(运算符重载函数)

用转换构造函数可以将一个指定类型的数据转换为类的对象。但是不能反过来将一个类的对象转换为一个其他类型的数据(例如将一个Complex类对象转换成double类型数据)。在C++提供类型转换函数(type conversion function)来解决这个问题。类型转换函数的作用是将一个类的对象转换成另一类型的数据。

类型转换函数的一般形式为:

 operator 类型名( ){ 实现转换的语句 }

下面是简单实现。这时候,Base起了两方面的作用:类和数据类型。系统会在需要的时候自动调用对应的类方法。

 #include  using namespace std; class Base{ private: float x; int y; public: Base (float xx=0,int yy=0){ x = xx; y = yy; } operator float (){ return x; } operator int (){ return y; } void display(){ cout<<"x is :"<<x<<";y is :"<<y<<endl; } }; int main() { Base base(1.0,2); base.display(); int y= base; float x= base; cout<<"NewX is :"<<x<<"NewY is:"<<y<<endl; return 0; }

基本运算符重载(自增自减)

主要总结 自增自减的前置和后置的用法。其他的加减乘除较简单。

简单的代码实现(纯语法)

 #include  using namespace std; class Base{ private: float x; int y; public: Base (float xx=0,int yy=0){ x = xx; y = yy; } operator float (){ return x; } operator int (){ return y; } Base operator ++(){//前置 ++ x++; y++; return *this; } Base operator --(){ x--; y--; return *this; } Base operator ++(int ){//后置 ++ Base temp = *this; ++(*this); return temp; } Base operator --(int ){ Base temp = *this; --(*this); return temp; } void display(){ cout<<"x is :"<<x<<";y is :"<<y<<endl; } }; int main() { Base base(1.0,1); Base tem = base++; base.display(); tem.display(); Base base2(1.0,1); tem = ++base2; base.display(); tem.display(); return 0; }

发现:

后置和前置的区别是有无int参数。

后置需要申请新的空间,大小是类的大小。所以,后置操作会有额外的时间空间开销。

尽量使用前置操作:如:for (int i=0;i<n;++i)

以上就是浅谈C++类型转化(运算符重载函数)和基本运算符重载(自增自减)的详细内容,更多请关注gaodaima搞代码网其它来源gaodai#ma#com搞*!代#%^码$网相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:浅谈C++类型转化(运算符重载函数)和基本运算符重载(自增自减)

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址