【发布时间】:2020-05-24 08:09:23
【问题描述】:
我正在写一个稀疏矩阵类,我想通过重载operator<<来输出稀疏矩阵。
我想知道如何启用 SMatrix (operator<<) 的好友功能直接(不是通过某些接口) 访问 TriTuple 的私有数据成员?请注意,SMatrix 同时是 TriTuple 的朋友类。见代码如下。
// tri-tuple term for sparse matrix by the form <row, col, value>
template<typename T>
class TriTuple {
template<typename U> friend class SMatrix;
// enable friend of SMatrix access private members of TriTuple
// declaring like this? feasible in VS2019, but not in gcc
template<typename U>
friend std::ostream& operator<<(std::ostream& os, const SMatrix<U>& M);
private:
size_t _row, _col;
T _val;
public:
//...
};
// sparse matrix
template<typename T>
class SMatrix {
template<typename U>
friend std::ostream& operator<<(std::ostream& os, const SMatrix<U>& M);
private:
size_t _rows, _cols;// # of rows & columns
size_t _terms; // # of terms
TriTuple<T>* _arr; // stored by 1-dimensional array
size_t _maxSize;
public:
//...
};
template<typename U>
std::ostream& operator<<(std::ostream& os, const SMatrix<U>& M)
{
M.printHeader();
for (size_t i = 0; i < M._terms; ++i) {
os << M._arr[i]._row << "\t\t" << M._arr[i]._col << "\t\t" << M._arr[i]._val << '\n';
}
return os;
}
在VS2019(可能是C++17)可以成功编译运行,但是在gcc中编译失败(目前只有c++11可用)。 那是c ++标准版的问题吗? (它指的是“ISO C++ 禁止声明......”)我应该如何改进声明? 请参阅下图中的错误消息。 gcc error_msg 提前谢谢你们了不起的家伙:-)
【问题讨论】:
-
经过多年的 c++ 和 python,我明白 private 只对保护类的不变量有意义。我会简单地删除 private 和 friend,使用关键字 struct 而不是 class 并访问我需要的值。
-
注意:GCC 在最近的版本中支持 C++17。编译时只需传递
-std=c++17选项即可。
标签: c++ templates sparse-matrix ostream friend-function