我認爲朋友功能可以訪問所有會員。即使在這個問題上,它的工作:
C++ friend function can't access private members朋友功能不允許訪問私人會員
在這個問題給出的答案似乎等同於我的代碼,他編細而我只是說array_是pivate。有人知道爲什麼
.H:
#ifndef matrix_h
#define matrix_h
#include <iostream>
using namespace std;
template <typename Comparable>
class matrix
{
private:
size_t num_cols_;
size_t num_rows_;
Comparable **array_;
public:
friend ostream& operator<< (ostream& o, const matrix<Comparable> & rhs);
size_t NumRows();
size_t NumCols();
};
#endif
的.cpp:
#include <iostream>
#include "matrix.h"
using namespace std;
template <typename Comparable>
ostream& operator<< (ostream& o, matrix<Comparable> & rhs){
size_t c = rhs.NumRows();
size_t d = rhs.NumCols();
for (int i = 0; i < c; i++){
for (int j = 0; j < d; j++){
o << rhs.array_[i][j]; //not allowed
}
o << endl;
}
return o;
}
template <typename Comparable>
size_t matrix<Comparable>::NumRows(){
return num_rows_;
}
template <typename Comparable>
size_t matrix<Comparable>::NumCols(){
return num_cols_;
}
int main(){
matrix<int> a;
cout << a << endl;
}
聲明瞭友元函數採取'常量矩陣&',但其定義中的一個'矩陣&'。它們不是同一個功能。 –
user657267
另請參見:[爲什麼模板只能在頭文件中實現?](http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file) – NathanOliver
如果我讓它們都是const,或者刪除const,那麼我會得到一個未定義的引用錯誤。未定義對運營商的引用<< – user3444650