簡體   English   中英

可以為嵌套的私有類重載operator <<嗎?

[英]Overloading operator<< for a nested private class possible?

如何為一個像這樣的嵌套私有類重載一個operator <<?

class outer {
  private:
    class nested {
       friend ostream& operator<<(ostream& os, const nested& a);
    };
  // ...
};

在外部類編譯器之外嘗試抱怨隱私時:

error: ‘class outer::nested’ is private

你可以讓operator<<也是outer朋友。 或者你可以在nested完全inline實現它,例如:

class Outer
{
    class Inner
    {
        friend std::ostream& 
        operator<<( std::ostream& dest, Inner const& obj )
        {
            obj.print( dest );
            return dest;
        }
        //  ...
        //  don't forget to define print (which needn't be inline)
    };
    //  ...
};

如果你想在兩個不同的文件(hh,cpp)中使用相同的東西,你必須給朋友兩次這個函數如下:

HH:

// file.hh
class Outer
{
    class Inner
    {
        friend std::ostream& operator<<( std::ostream& dest, Inner const& obj );
        // ...
    };

    friend std::ostream& operator<<( std::ostream& dest, Outer::Inner const& obj );
    //  ...
};

CPP:

// file.cpp:
#include "file.hh"

std::ostream    &operator<<( std::ostream& dest, Outer::Inner const& obj )
{
    return dest;
}

暫無
暫無

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

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