【问题标题】:How do I assign a certain value from an object to a long variable?如何将对象中的某个值分配给 long 变量?
【发布时间】:2011-04-10 22:14:01
【问题描述】:

例子:

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' to long int'

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

当左侧是普通变量而不是对象时,如何在类之外定义一个 operator=?

【问题讨论】:

    标签: c++ operator-overloading operator-keyword


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-07-29
        • 2020-02-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多