是否可以将对象分配给int?

编程入门 行业动态 更新时间:2024-10-20 03:44:22
本文介绍了是否可以将对象分配给int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个CCounter类,该类保存并具有由互斥锁保护的整数值.我已经定义了多个运算符,例如post/pre inc/dec返回一个整数,所以我可以这样做:

I have a CCounter class which holds and integer value protected by mutex. I've defined several operators like post/pre inc/dec returning an integer so I can do:

CCounter c(10); int i = c++;

但是如何处理像i = c这样的简单任务呢?我试图定义朋友operator =,但是它给了我

but what do I do with a simple assignment like i = c ? I tried to define friend operator= but it gives me

operator=(int&, const CCounter&)’ must be a nonstatic member function

错误.请指教.谢谢.

推荐答案

您需要定义一个从CCounter转换为int的转换运算符.将此成员添加到您的班级:

You need to define a casting operator that casts from CCounter to int. Add this member to your class:

operator int() const { return ...; }

更多推荐

是否可以将对象分配给int?

本文发布于:2023-07-29 08:52:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1239237.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象   int

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!