是否可以将对象分配给int?
我有一个 CCounter 类,它保存受互斥锁保护的整数值。 我已经定义了几个运算符,例如 post/pre inc/dec 返回一个整数,这样我就可以执行以下操作:
CCounter c(10);
int i = c++;
但是我该如何处理像 i = c
这样的简单赋值呢? 我尝试定义友元运算符=,但它给了我
operator=(int&, const CCounter&)' 必须是非静态成员函数
错误。 请指教。 谢谢。
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++;
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
error. Please, advise. Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
您需要定义一个从 CCounter 转换为 int 的转换运算符。 将此成员添加到您的班级中:
You need to define a casting operator that casts from CCounter to int. Add this member to your class:
正如您所发现的,赋值运算符必须是类的成员函数。 由于整数不是类,因此您不能为它们编写operator=()。 正如其他人指出的那样,另一种选择是编写一个转换为 int 的函数。 我强烈建议您编写一个像 ToInt() 这样的命名函数来执行此操作,而不是使用转换运算符,这可能是不明显错误的根源。
As you have found out, the assignment operator must be a member function of a class. As ints are not classes, you can't write operator=() for them. The alternative, as others have pointed out is to write a function that converts to an int. I would strongly suggest you write a named function like ToInt() to do this, rather than using a conversion operator, which can be the source of non-obvious bugs.
天哪,
如果您只是“获取”计数器的当前值,您不应该定义一个访问器函数吗?
比如:
任何其他的事情都在某种程度上掩盖了你想要做的事情的意图。 恕我直言,纳奇! (-:
HTH
欢呼,
G'day,
Shouldn't you be defining an accessor function instead if you're just "getting" the current value of the counter?
Something like:
Anything else is sort of disguising the intention of what you're trying to do. IMHO Natch! (-:
HTH
cheers,
您需要定义
operator int()
以允许将您的类转换为int。 例如:You need to define
operator int()
to allow the conversion of your class to an int. For example:如前所述,使用 int() 运算符。 这里是一个代码片段:
As said use the int() operator. Here a code snippet :
你说:
既然其他答案为您提供了将对象转换为整数的通用方法,我建议您更改这些其他运算符,以便它们的行为符合通常的预期。
例如,预增量通常返回对对象本身的引用,而后增量通常返回原始对象的临时副本(在增量之前)。
You said:
Now that other answers provided you with a generic way to convert the object to an integer, I would recommend that you change these other operators so that they behave as typically expected.
For instance, pre increment typically returns a reference to the object itself, and post increment typically returns a temporary copy of the original object (prior to the incrementation).
尽管您已获得有效的解决方案 ,我还会考虑简单地创建一个返回 int 的普通函数,例如
int GetValue() const
,以提高可读性和易于维护。 当然,这是非常主观的。Although you have been given a valid solution, I would also consider simply creating a normal function which returns int, such as
int GetValue() const
, to improve readability and ease of maintenance. Of course this is highly subjective.