如题,可以重载 operator = 来进行转换吗? 我有一个简单的类。
class A{
protected:
int m_int;
public:
A& operator=( int& obj)
{
m_int = obj;
return *this;
}
};
我要:
A t_a = 1;
和
int t_int = t_a;
有办法吗?
最佳答案
只需定义转换运算符
operator int() const
{
return m_int;
}
或
explicit operator int() const
{
return m_int;
}
在最后一种情况下,您必须在语句中使用显式转换
int t_int = int( t_a );
考虑到赋值运算符应该像这样声明
A& operator=( const int& obj)
{
m_int = obj;
return *this;
}
或者喜欢
A& operator=( int obj)
{
m_int = obj;
return *this;
}
否则无法将非常量引用与整型字面量或临时值绑定(bind)。
至于赋值运算符,您可以只为类型 int
和类型 A
定义复合赋值运算符。
例如,您可以定义 operator +=
或其他运算符。
关于c++ - 重载运算符 = 用于类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47091058/