c++ - "invalid use of non-static data member"当通过友善的输出运算符访问模板化类的字段时

标签 c++ templates friend

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

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;

最佳答案

看起来您打算将友元函数命名为 operator<<而不是 ostream :

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

您还需要访问 tab作为 t 的成员:

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

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

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

关于c++ - "invalid use of non-static data member"当通过友善的输出运算符访问模板化类的字段时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16002417/

相关文章:

C++11线程修改std::list

c++ - 动态分配二维 vector C++

html - mailchimp 模板导出到带有合并标签的 mandrill 问题

c++ - Visual Studio 2019 C++ 无法识别模板 friend

c++ - 单个成员而不是全类的 friend 声明?

c++ - Visual C++、std 和 getline(ifstream, string)、EOF 在 std 堆栈内抛出和中断,这正常吗?

c++ - Qt5不会发送超时信号

c++ - 从模板继承?

python - 为 Django 模板创建继承图/树

c++ - Friend C++ 类的非常量模板化版本