C++ 运算符重载:将 A 的类型 B 的属性值分配给 B 对象

C++ Operator overloading: assign A's attribute value of type B to a B object

本文关键字:属性 分配 对象 运算符 类型 C++ 重载      更新时间:2023-10-16

std::string 类允许在此运算符的帮助下从不同的类型(例如 'char'、'const char*' 和 'std::string' )分配其内部值。为了实现以下目标,需要重载哪个运算符?

class A {
public:
    A(std::string value)
        : m_value(value)
    {
    }
    // A a = std::string("some value")
    A& operator=(const std::string value) {
        m_value = value;
    }
    // std::string someValue = A("blabla")
    ???? operator ????
private:
    std::string m_value;
};

之后,我们应该能够通过 A 对象访问 std::string 的函数,例如:

A a("foo");
printf("A's value: %s n", a.c_str());
您需要

使class A能够将自身转换为类型 string

这看起来像:

class A
{
public:
    operator std::string() const { return m_value; }
};

之后,您可以执行以下操作:

printf("A's value: %s n", ((std::string)a).c_str());

或者,您可以重载->运算符:

class A
{
public:
    const std::string* operator->()const { return & m_value; }
}
printf("A's value: %s n", a->c_str());

IDEOne link