【问题标题】:Can assignment operator be overloaded to return the value of a property of a class?可以重载赋值运算符以返回类属性的值吗?
【发布时间】:2026-02-14 01:35:04
【问题描述】:

我想使用赋值运算符返回一个类的属性值。我试图实现这个目的。我在网上搜索了很多,但我访问的所有网站都谈到了如何重载赋值运算符来像这样的类的复制构造函数:class_t& operator=(class_t&);。谁能帮我重载此运算符以返回类属性的值?

这是我的代码:

class A_t
{
private:
  int value = 0;

public:
  int operator = (A_t);  // I failed to overload assignment operator for this
  A_t& operator = (int); // I succeeded to overload assignment operator for this
  int Value();
  void setValue(int);
};

A_t& A_t::operator = (int value)
{
  this->setValue(value);
  return *this;
}

int operator = (A_t &data)
{
  return data.value;
}

int A_t::Value() { return this->value; }
void A_t::setValue(int data) { this->value = data; }

int main()
{
    A_t object = 3;
    int value = object; // Error: cannot convert 'A_t' to 'int' in initialization

    cout << value << endl;
    return 0;
}

【问题讨论】:

  • 我建议您检查您的方法,因为您在使用复制构造函数的签名时试图重载赋值运算符。见 *.com/questions/12688942/…>

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


【解决方案1】:

不能为此重载operator =。您可以做的是重载类中的隐式转换为int 运算符:

operator int() const { return value; }

但是,请仔细考虑这是否真的适合您的情况。通常应该不惜一切代价避免隐式转换,因为它非常容易出错(许多聪明人认为 C++ 根本不应该允许定义自定义隐式转换!)。

【讨论】:

  • 那么,通过在声明前添加explicit 关键字来明确说明会更好吗?
  • @AmirMohsen 是的,几乎总是这样。
【解决方案2】:

为此,您的类需要一个int 运算符,该运算符在分配给整数时返回变量。另外,该类错过了 A_t object = 3; 所需的构造函数。修正后的类是这样的,

class A_t
{
private:
    int value = 0;

public:
    //int operator = (A_t);  <-- You dont need this.
    A_t& operator = (int); // I succeeded to overload assignment operator for this
    int Value();
    void setValue(int);

    /**
     * Construct using an integer value.
     * 
     * @param val: The value to be set.
     */
    A_t(int val) : value(val) {}

    /**
     * int operator.
     * 
     * @return The value stored inside.
     */
    operator int() const
    {
        return value;
    }

    /**
     * int& operator (optional).
     *
     * @return The variable stored inside.
     */
    operator int& ()
    {
        return value;
    }
};

A_t& A_t::operator = (int value)
{
    this->setValue(value);
    return *this;
}

int A_t::Value() { return this->value; }
void A_t::setValue(int data) { this->value = data; }

int main()
{
    A_t object = 3;
    int value = object; // Error: cannot convert 'A_t' to 'int' in initialization

    cout << value << endl;
    return 0;
}

【讨论】: