如何将一个对象的某个值赋给一个长变量?
问题描述:
long a;
BoundedCounter e;
所以我想在班上分配私有变量计数器的值的。
a=e;
使用这种尝试:
long int & operator=(long b)
{
b=counter;
return b;
}
和
long int & operator=(long b, BoundedCounter &a)
{
b=a.getCounter();
return b;
}
它会返回一个编译错误:
cannot convert
BoundedCounter' to
long int' in assignment
和
`long int& operator=(long int, BoundedCounter&)' must be a nonstatic member function
如何定义一个operator =在类左边是一个普通变量而不是对象的情况下工作的类之外?
答
operator=
在这里是不合适的,因为赋值的左边是原始类型(并且不能为原始类型定义operator=
)。尝试给BoundedCounter
的operator long
,如:
class BoundedCounter {
private:
long a_long_number;
public:
operator long() const {
return a_long_number;
}
};
分配:
class BoundedCounter
{
public:
// ...
operator long() const
{
return counter;
// or return getCounter();
}
};
答
你的代码是从一个BoundedCounter
到long
所以你需要定义转换(CAST)运营商从BoundedCounter
到long
转换您定义的运算符将允许您将long
值分配给BoundedCounter
类的实例,这与您尝试执行的操作相反。
工作!非常感谢 :) – alabroski 2011-04-10 22:23:18