簡體   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