簡體   English   中英

C ++-ostream(<<)重載

[英]C++ - ostream (<<) overloading

我想知道是否有任何方法可以將類的<<運算符重載而不將其聲明為朋友函數。 我的教授說,這是唯一的方法,但是我想知道他是否不知道還有另一種方法。

只要您希望通過類的公共接口訪問要輸出的所有內容,就無需使operator <<函數成為該類的朋友。

是的你可以

std::ostream& operator<<(std::ostream &stream, WHATEVER_TYPE var) {
    std::string str = somehowstringify(var);
    return stream << str;
}

但是請注意,由於它是非成員非朋友功能,因此它當然只能訪問std::ostream的公共接口,這通常不是問題。

是的,一種方法是這樣的:

class Node
{
public:
    // other parts of the class here
    std::ostream& put(std::ostream& out) const { return out << n; };
private:
   int n;
};

std::ostream& operator<<(std::ostream& out, const Node& node) {
    return node.put(out);
}

僅當您需要訪問它的私有成員時,才需要將其聲明為朋友功能
在以下情況下,您始終可以在不使用好友功能的情況下執行此操作:
1)不需要私人成員訪問。
2)您提供了一種以其他方式訪問您的私人成員的機制。 例如

class foo
{
    int myValue;
    public:
    int getValue()
    {
        return myValue;
    }
}

正如R Sahu所指出的那樣,要求是操作員應該能夠訪問其必須顯示的所有內容。

這里有一些可能的選擇

1,將重載函數添加為好友函數

2使用公共訪問器方法或公共數據成員使該函數可以訪問該類的所有必需數據成員

class MyClass {
   private:
   int a;
   int b;
   int c;
   public:
   MyClass(int x,int y,int z):a(x),b(y),c(z) {};
   MyClass():a(0),b(0),c(0) {};
   int geta() { return a; }
   int getb() { return b; }
   int getc() { return c; }
};

std::ostream& operator<<(std::ostream &ostr,MyClass &myclass) {
   ostr << myclass.geta()<<" - " << myclass.getb() << " - " << myclass.getc() ;
   return ostr;
}


int main (int argc, char const* argv[])
{
   MyClass A(4,5,6);
   cout << A <<endl;

        return 0;
}

3.添加一個公共幫助程序函數,例如output帶有簽名std::ostream& output(std::ostream& str) ,然后在運算符函數中使用它。

暫無
暫無

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

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