作为每个C ++新手,我都在编写自己的矩阵类作为练习。我正在使用这样的类模板:
template<typename T>
class BMatrix {
public:
// Constructors
BMatrix(unsigned nrows, unsigned ncols);
BMatrix(unsigned nrows, unsigned ncols, T ival);
BMatrix(const BMatrix<T>& a);
// Destructor
~BMatrix();
// Access
T& operator() (unsigned row, unsigned col);
T operator() (unsigned row, unsigned col) const;
// ...
// Friends
//friend BDiagonal<T>::BDiagonal(unsigned size, T val);
private:
unsigned nrows_, ncols_;
T* data_;
};
BMatrix的构造函数分配大小为nrows_ * ncols_的数组data_。
现在,如您所见,我想将另一个类BDiagonal的构造函数声明为好友。 BDiagonal类是BMatrix的派生类。其背后的动机是BDiagonal将节省内存(我只需要存储nxn对角矩阵的n个非零元素),并使某些操作更快。因此,我希望此矩阵的构造函数分配大小为nrows * 1的数组data_,但nrows_和ncols_仍大于1。这样,我仍然可以使用为BMatrix类实现的某些功能(例如重载) <<操作符以打印矩阵)。
毫不奇怪,它没有编译,而是编译器抛出错误:
BArray/core.h:86:9: error: ‘BDiagonal’ does not name a type
friend BDiagonal<T>::BDiagonal(unsigned size, T val);
如果我在文件开头声明BDiagonal,则会得到:
BArray/core.h:546:7: error: invalid use of incomplete type ‘class BMatrix<double>’
class BDiagonal : public BMatrix<T> {
^~~~~~~~~
BArray/core.h:55:7: note: declaration of ‘class BMatrix<double>’
class BMatrix {
我也尝试过向前声明BMatrix,但这会导致更多错误。我不想声明BMatrix的私有成员受到保护,因为这将导致任何人都可以通过派生一个类直接访问它们。
有没有办法做到这一点?更重要的是,我是否有任何理由不应该这样做,而对我的BDIagonal班采取不同的方法?
干杯
如果您需要某些东西可以在派生类中访问,请使其受保护而不是私有。在这种情况下,您不需要朋友。
You might also add a protected constructor in
BMatrix
that initializesdata_
with the desired number of elements that you could call (delegate) in your derived class constructor.