如何将对象中的某个值分配给 long 变量?

发布于 2024-10-31 21:33:58 字数 630 浏览 4 评论 0原文

例子:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

花辞树 2024-11-07 21:33:58

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

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

operator= is unsuitable here as the left-hand side of the assignment is a primitive type (and you cannot define operator= for primitive types). Try giving BoundedCounter an operator long, e.g.:

class BoundedCounter
{
public:
    // ...
    operator long() const
    {
        return counter;
        // or return getCounter();
    }
};
挽梦忆笙歌 2024-11-07 21:33:58

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

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

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

Your code is converting from a BoundedCounter to a long so you need to define a conversion (cast) operator from BoundedCounter to long:

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

The assignment operator that you had defined would allow you to assign a long value to an instance of the BoundedCounter class which is the opposite of what you are trying to do.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文