![](/img/trans.png)
[英]C++ Overloading assignment operator: “cannot convert `B*` to `A*`” error
[英]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());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.