c++ - 可以重载赋值运算符以返回类属性的值吗?
问题描述
我想使用赋值运算符返回类的属性值。我试图实现这个目的。我在网上搜索了很多,但我访问的所有网站都谈到了如何重载赋值运算符来像这样的类的复制构造函数: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;
}
解决方案
为此,您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;
}
推荐阅读
- facebook - FacebookAds\Http\Exception\AuthorizationException,代码:17:(#17)达到用户请求限制
- visualization - 在 power bi 中显示切片器值内没有数据的项目
- amazon-web-services - 如何对 AWS AppSync 架构进行版本控制
- angular - 将数据加载到网格后不显示滚动条
- ios - 单元格更新数据库后,UI 阻塞;我该如何解决?
- java - LSP(里氏替换原则)如何工作
- r - 在 R 中使用 formattable 组合列
- php - PHP/Laravel:只要有事情发生就运行函数
- java - 如何使用 context.xml 正确连接到 XAMPP mySQL DB
- python - 预计会看到 1 个数组,但得到了以下 4 个数组的列表