【发布时间】:2015-09-10 01:15:34
【问题描述】:
我认为朋友功能可以访问所有成员。即使在这个问题上它也有效:
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;
}
【问题讨论】:
-
您已声明朋友函数采用
const matrix<Comparable> &,但它的定义采用matrix<Comparable> &。它们的功能不同。 -
如果我将它们都设为 const 或删除 const,则会出现未定义的引用错误。对运算符 的未定义引用
-
危险:Rule of Three 违规。如果复制或移动矩阵,您的矩阵将出现不幸且可能致命的行为。
-
我有一个构造函数/析构函数/复制重载。我只是没有包括它,因为它无关紧要。我也不应该使用 .cpp 吗?
标签: c++ operator-overloading friend