问题描述:

类声明:student.h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
...
namespace Studenti {
class Student : private std::string, private std::valarray<double> {
private:
typedef std::valarray<double> ArrayDb;
std::ostream& arr_out(std::ostream& os) const;

public:
Student();

...

friend std::ostream& operator<<(std::ostream& os, const Student& stu);
};
}

类定义:student.cpp

1
2
3
4
5
6
7
8
9
10
11
#include "student.h"
...

using namespace Studenti;

ostream& operator<<(ostream& os, const Student& stu) {
os << "Scores for " << (const string&)stu << ":\n";
stu.arr_out(os);
return os;
}
...

这里编译器直接给 stu.arr_out(os) 标红,说无法访问类的私有成员。很是奇怪,为什么加了给类加上命名空间后友元函数无法访问类的私有成员呢?

在这里 friend function within a namespace 找到了解决方法。修改方式有两种

一、

  1. 修改 student.h 文件中的代码为
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
...
namespace Studenti {
class Student : private std::string, private std::valarray<double> {
private:
typedef std::valarray<double> ArrayDb;
std::ostream& arr_out(std::ostream& os) const;

public:
Student();

...

friend std::ostream& operator<<(std::ostream& os, const Student& stu);
};
std::ostream& operator<<(std::ostream& os, const Student& stu);
}
  1. 修改 student.cpp 文件中的代码为
1
2
3
4
5
6
7
8
9
10
11
12
13
#include "student.h"
...

using namespace Studenti;

ostream& Studenti::operator<<(ostream& os, const Student& stu) {
os << "Scores for " << (const string&)stu << ":\n";
stu.arr_out(os);
return os;
}

...

二、

  1. 同第一种方式里的1

  2. 修改 student.cpp 文件中的代码为

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include "student.h"
...

using namespace Studenti;

namespace Studenti {
ostream& operator<<(ostream& os, const Student& stu) {
os << "Scores for " << (const string&)stu << ":\n";
stu.arr_out(os);
return os;
}
}

...