簡體   English   中英

C ++中自定義字符串類的<<運算符函數的返回值

[英]Return value for a << operator function of a custom string class in C++

我正在嘗試創建自己的std :: string包裝器來擴展其功能。 但是在聲明<<運算符時遇到了問題。 到目前為止,這是我的代碼:

我的自定義字符串類:

class MyCustomString : private std::string
{
public:
  std::string data;
  MyCustomString() { data.assign(""); }
  MyCustomString(char *value) { data.assign(value); }
  void Assign(char *value) { data.assign(value); }
  // ...other useful functions
  std::string & operator << (const MyCustomString &src) { return this->data; }
};

主程序:

int main()
{
  MyCustomString mystring("Hello");
  std::cout << mystring; // error C2243: 'type cast' : conversion from 'MyCustomString *' to 'const std::basic_string<_Elem,_Traits,_Ax> &' exists, but is inaccessible

  return 0;
}

我希望cout將該類視為std :: string,因此我不需要執行以下操作:

std::cout << mystring.data;

任何形式的幫助將不勝感激!

謝謝。

只是fyi:我的IDE是Microsoft Visual C ++ 2008 Express Edition。

如果你看看如何聲明所有流操作符,它們的形式如下:

ostream& operator<<(ostream& out, const someType& val );

基本上,您希望重載函數實際執行輸出操作,然后返回新更新的流操作符。 我建議做的是以下內容,請注意這是一個全局函數,而不是您的類的成員:

ostream& operator<< (ostream& out, const MyCustomString& str )
{
    return out << str.data;
}

請注意,如果您的“數據”對象是私有的,可能應該使用哪個基本OOP,則可以在內部將上述運算符聲明為“朋友”函數。 這將允許它訪問私有數據變量。

你需要一個獨立的功能(你班上的朋友,如果你把你的data設為私有你可能應該!)

inline std::ostream & operator<<(std::ostream &o, const MyCustomString&& d)
{
    return o << d.data;
}

這不是你重載<<運算符的方式。 你需要傳入一個對ostream的引用並返回一個(所以你可以堆疊多個<<,就像std::cout << lol << lol2 )。

ostream& operator << (ostream& os, const MyCustomString& s);

然后就這樣做:

ostream& operator << (ostream& os, const MyCustomString& s)
{
   return os << s.data;
}

首先,您似乎遇到了MyCustomString定義的問題。 它從std::string私下繼承,並包含std::string本身的實例。 我會刪除其中一個。

假設您正在實現一個新的字符串類,並且希望能夠使用std::cout輸出它,您需要一個強制轉換操作符來返回std::cout期望的字符串數據:

operator const char *()
{
    return this->data.c_str();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM