如何将对象中的某个值分配给 long 变量?
例子:
long a;
BoundedCounter e;
所以我想把类中私有变量counter的值赋给a。
a=e;
尝试使用这个:
long int & operator=(long b)
{
b=counter;
return b;
}
并
long int & operator=(long b, BoundedCounter &a)
{
b=a.getCounter();
return b;
}
返回编译错误:
无法将
BoundedCounter' 转换为
赋值中的 long int
和
`长整型& operator=(long int, BoundedCounter&)' 必须是非静态成员函数
如何在类外部定义一个operator=,当左侧是普通变量而不是对象时,它将起作用?
Example:
long a;
BoundedCounter e;
So I want to assign the value of the private variable counter in the class to a.
a=e;
Tried using this:
long int & operator=(long b)
{
b=counter;
return b;
}
and
long int & operator=(long b, BoundedCounter &a)
{
b=a.getCounter();
return b;
}
Which return a compile error:
cannot convert
BoundedCounter' to
long int' in assignment
and
`long int& operator=(long int, BoundedCounter&)' must be a nonstatic member function
How do I define an operator= outside of the class which will work when the left side is a normal variable and not an object?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
operator=
在这里不合适,因为赋值的左侧是基本类型(并且您不能为基本类型定义operator=
)。尝试给BoundedCounter
一个operator long
,例如:operator=
is unsuitable here as the left-hand side of the assignment is a primitive type (and you cannot defineoperator=
for primitive types). Try givingBoundedCounter
anoperator long
, e.g.:您的代码正在从
BoundedCounter
转换为long
,因此您需要定义一个从BoundedCounter
到long< 的转换(强制转换)运算符/code>:
您定义的赋值运算符将允许您将
long
值分配给BoundedCounter
类的实例,这与您想要的相反做。Your code is converting from a
BoundedCounter
to along
so you need to define a conversion (cast) operator fromBoundedCounter
tolong
:The assignment operator that you had defined would allow you to assign a
long
value to an instance of theBoundedCounter
class which is the opposite of what you are trying to do.