当我尝试通过友好的输出运算符访问模板化类的字段时出现以下错误。
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/