![](/img/trans.png)
[英]How to initialize private members of a class using a friend function in C++?
[英]How to enable a friend class's friend function access its private members directly in C++
我正在编写一个稀疏矩阵 class,我想通过重载operator<<
来 output 稀疏矩阵。 我想知道如何让 SMatrix 的朋友 function ( operator<<
)直接(不是通过某些接口)访问 TriTuple 的私有数据成员? 请注意,SMatrix 同时是 TriTuple 的朋友 class。 见代码如下。
// 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 提前谢谢你们了不起的家伙:-)
此错误与 class SMatrix
的前向声明有关。 只是尝试转发声明
template<typename T>
class SMatrix;
在TriTuple
。
在godbolt上检查
在operator<<
中也没有检查空矩阵。 我建议您对 gcc 使用-fsanitize=undefined -fsanitize=address
。
如果友元声明出现在本地 class ( [class.local] ) 中并且指定的名称是非限定名称,则在不考虑最内层封闭非类 scope 之外的范围的情况下查找先前声明。 给朋友 function 声明,如果没有事先声明,程序是病态的。 对于朋友class声明,如果没有事先声明,则指定的class属于最内层的封闭非类scope,但如果随后通过nameup找到匹配的声明,则在查找之前没有提供其名称最里面的非类 scope。
您需要提供SMatrix
的定义或至少在引用它之前对其进行前向声明:
template <typename U>
class SMatrix;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.