0

当我尝试通过友好的输出运算符访问模板化类的字段时,出现以下错误。

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’

这是我写的确切代码:

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;
4

1 回答 1

1

看起来您打算命名朋友函数operator<<而不是ostream

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

您还需要以tab成员身份访问t

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

这是因为,尽管您在类定义中定义了朋友函数,但它具有命名空间范围:

在类中定义的友元函数在定义它的类的(词法)范围内。

于 2013-04-14T18:03:10.847 回答