我正在编写一个稀疏矩阵类,我想通过重载 operator<<
来输出稀疏矩阵。
我想知道如何启用 SMatrix ( operator<<
) 的友元函数直接(不是通过某些接口(interface))访问 TriTuple 的私有(private)数据成员?请注意,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 提前谢谢你们了不起的人:-)
最佳答案
If a friend declaration appears in a local class ([class.local]) and the name specified is an unqualified name, a prior declaration is looked up without considering scopes that are outside the innermost enclosing non-class scope. For a friend function declaration, if there is no prior declaration, the program is ill-formed. For a friend class declaration, if there is no prior declaration, the class that is specified belongs to the innermost enclosing non-class scope, but if it is subsequently referenced, its name is not found by name lookup until a matching declaration is provided in the innermost enclosing non-class scope.
您需要提供 SMatrix
的定义,或者至少在引用它之前对其进行前向声明:
template <typename U>
class SMatrix;
关于c++ - 如何在 C++ 中使友元类的友元函数直接访问其私有(private)成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61983237/