如何启用好友类的好友功能,直接在C ++中访问其私有成员

问题描述 投票:3回答:2

我正在编写一个稀疏矩阵类,并且我想通过重载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++ templates sparse-matrix ostream friend-function
2个回答
1
投票

如果朋友声明出现在本地类([class.local])中,并且指定的名称是不合格名称,则在不考虑最内层非类范围之外的范围的情况下,查找先前的声明。对于朋友函数声明,如果没有事先声明,则程序格式错误。对于朋友类声明,如果没有先前的声明,则指定的类属于最内层的封闭非类范围,在最里面的非类作用域中提供。


1
投票
© www.soinside.com 2019 - 2024. All rights reserved.