繁体   English   中英

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

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

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链接

C ++ <

[英]C++ <<operator overloading with same type

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM