c++ - 如何在 C++ 中使友元类的友元函数直接访问其私有(private)成员

标签 c++ templates sparse-matrix ostream friend-function

我正在编写一个稀疏矩阵类,我想通过重载 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 提前谢谢你们了不起的人:-)

最佳答案

[class.friend]/p11 :

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/

相关文章:

C++:是什么导致了这个堆栈粉碎错误?

php - 使用 Smarty 或 Backbone.js 制作 javascript 模板

python - scipy 稀疏矩阵的乘法运算符

python - 从稀疏 coo_matrix 获得的对角稀疏矩阵

c++ - QPixmap 的 loadFromData 函数使用了一些奇怪的缓存机制?

priority_queue模板中的c++编译错误

c++ - Olve Maudal 的 C++ 测验背后的解释(别名模板)

使用 C 中的链表创建稀疏矩阵

c++ - 我的所有方法都出现错误 c2084,但每个方法只有一个主体

c++ - 如何在类声明之外声明模板函数