c++ - 重载运算符 = 用于类型转换

标签 c++ operator-overloading

如题,可以重载 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/

相关文章:

c++ - *this-> 不能作为函数使用

c++ - 如何在基派生类中重载运算符?

c++ - 迭代 std::string C++

c++ - Xcode 和 Objective-C++ 找不到 <cstdio>

C++ 元编程 : overloading of arithmetic operators for types

c++ - 使用 >> 运算符重载时出错

C++:后增量导致相同的值

c++ - Qt,如何从文件中重复读取数据?

c++ - 自引用类

面试在线测试中的c++运算符重载问题