如何将对象中的某个值赋给长变量

How do I assign a certain value from an object to a long variable?

本文关键字:变量 对象      更新时间:2023-10-16

示例:

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;
}

返回编译错误:

无法在分配中转换BoundedCounter' to long int

`long int&operator=(long int,BoundedCounter&('必须是非静态成员函数

当左边是普通变量而不是对象时,我如何在类之外定义一个运算符=?

operator=在这里不合适,因为赋值的左侧是基元类型(不能为基元类型定义operator=(。尝试给BoundedCounter一个operator long,例如:

class BoundedCounter
{
public:
    // ...
    operator long() const
    {
        return counter;
        // or return getCounter();
    }
};

您的代码正在从BoundedCounter转换为long,因此您需要定义一个从BoundedCounterlong:的转换(强制转换(运算符

class BoundedCounter {
private:
    long a_long_number;
public:
    operator long() const {
        return a_long_number;
    }
};

您定义的赋值运算符将允许您将long值分配给BoundedCounter类的实例,这与您尝试执行的操作相反。