简体   繁体   中英

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

The std::string class allows assigning its internal value from different types, such as 'char', 'const char*' and 'std::string', with the help of this operator. Which operator is needed to be overloaded in order to achieve the following?

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;
};

After that, we should be able to access std::string's functions through the A object, for example:

A a("foo");

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

You need to make it possible for class A to convert itself to type string .

This looks like:

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

After that, you can do this:

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

Alternately, you can overload the -> operator:

class A
{
public:
    const std::string* operator->()const { return & m_value; }
}

printf("A's value: %s \n", a->c_str());

IDEOne link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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