简体   繁体   中英

“invalid use of non-static data member” when accessing a templated class' field through befriended output operator

I get the following error when I try to access a templated class'es field through befriended output operator.

Database.hpp: In function ‘std::ostream& ostream(std::ostream&, const Table<T, S>&)’:
Database.hpp:10:12: error: invalid use of non-static data member ‘Table<T, S>::tab’
Database.hpp:41:19: error: from this location
Database.hpp: In function ‘std::ostream& operator<<(std::ostream&, const List&)’:
Database.hpp:62:17: error: no match for ‘operator<<’ in ‘os << l.List::AnnouncementDate’

here is the exact code I wrote:

template <class T, int S>
class Table
{
    T tab[S];
    public:
    inline T& operator[](int i)
    {
        return tab[i];
    }
    inline const T& operator[](int i) const
    {
        return tab[i];
    }
    Table() {}
    ~Table() {}
    Table(const Table &t)
    {
        for ( int i=0; i<S; ++i )
        {
            tab[i] = t[i];
        }
    }
    Table& operator=(const Table &t)
    {
        for ( int i=0; i<S; ++i )
        {
            tab[i] = t[i];
        }
        return *this;
    }
    friend std::ostream& ostream( std::ostream& os, const Table<T,S> &t )
    {
        for ( int i=0; i<3; os << '-' )
        {
            os << tab[i++];
        }
        return os;
    }
};

typedef Table<int,3> Date;

struct List
{
    Date AnnouncementDate;
    int BonusShares;
    int StockSplit;
    int CashDividend;
    bool DividendPayment;
    Date ExDividendDate;
    Date ShareRecordDate;
    Date BonusSharesListingDate;

    friend std::ostream& operator<<( std::ostream& os, const List &l )
    {
        os << l.AnnouncementDate << ',' << std::endl <<
        l.BonusShares << ',' << std::endl <<
        l.StockSplit << ',' << std::endl <<
        l.CashDividend << ',' << std::endl <<
        l.DividendPayment << ',' << std::endl <<
        l.ExDividendData << ',' << std::endl <<
        l.ShareRecordDate << ',' << std::endl <<
        l.BonusSharesListingDate << ',' << std::endl;
        return os;
    }
};

typedef std::vector<List> Database;

Looks like you meant to name the friend function operator<< instead of ostream :

friend std::ostream& operator<<( std::ostream& os, const Table<T,S> &t )
//                   ^^^^^^^^^^

You'll also need to access tab as a member of t :

os << t.tab[i++];

This is because, although you defined the friend function inside your class definition, it has namespace scope:

A friend function defined in a class is in the (lexical) scope of the class in which it is defined.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM