|
|
20鱼币
// studentc.h
#ifndef STUDENTC_H_
#define STUDENTC_H_
#include <iostream>
#include <string>
#include <valarray>
class Student
{
private:
typedef std::valarray<double> ArrayDb;
std::string name;
ArrayDb scores;
std::ostream & arr_out(std::ostream & os) const;
public:
Student() : name("Null Student"), scores() {}
Student(const std::string & s)
: name(s), scores() {}
explicit Student(int n)
: name("Nully"), scores(n) {}
Student(const std::string & s, int n)
: name(s), scores(n) {}
Student(const char * str, const double * pd, int n)
: name(str), scores(pd, n) {}
~Student() {}
friend std::ostream & operator<< (std::ostream & os, // 有元函数
Student & stu);
};
#endif
*****************************************************
// student.cpp
#include "studentc.h"
#include <iostream>
using std::ostream;
using std::endl;
using std::istream;
using std::string;
ostream & Student::arr_out(ostream & os) const
{
int i;
int lim = scores.size();
if (lim > 0)
{
for (i = 0; i < lim; i++)
{
os << scores[i] << " ";
if (i % 5 == 4)
os << endl;
}
if (i % 5 != 0)
os << endl;
}
else
{
os << " empty array";
}
return os;
}
ostream & operator<< (ostream & os, const Student & stu)
{
os << "Scores for" << stu.name << ":\n";
stu.arr_out(os);
return os;
}
//******************************************
编译结果:
1>------ 已启动生成: 项目: 483_student, 配置: Debug Win32 ------
1>正在编译...
1>student.cpp
1>f:\c++\c++ prime plus\课本程序\第十四章\483_student\483_student\student.cpp(36) : error C2248: “Student::name”: 无法访问 private 成员(在“Student”类中声明)
1> f:\c++\c++ prime plus\课本程序\第十四章\483_student\483_student\studentc.h(12) : 参见“Student::name”的声明
1> f:\c++\c++ prime plus\课本程序\第十四章\483_student\483_student\studentc.h(9) : 参见“Student”的声明
1>f:\c++\c++ prime plus\课本程序\第十四章\483_student\483_student\student.cpp(37) : error C2248: “Student::arr_out”: 无法访问 private 成员(在“Student”类中声明)
1> f:\c++\c++ prime plus\课本程序\第十四章\483_student\483_student\studentc.h(14) : 参见“Student::arr_out”的声明
1> f:\c++\c++ prime plus\课本程序\第十四章\483_student\483_student\studentc.h(9) : 参见“Student”的声明
1>生成日志保存在“file://f:\C++\C++ prime plus\课本程序\第十四章\483_student\483_student\Debug\BuildLog.htm”
1>483_student - 2 个错误,0 个警告
========== 生成: 成功 0 个,失败 1 个,最新 0 个,跳过 0 个 ==========
用的是vs2008, 用vc++ 6.0 也试过了也一样,还有c-free。都不行,所有发帖求助啊。哪位大牛帮帮忙~~~~
|
最佳答案
查看完整内容
友元函数声明是:
friend std::ostream & operator
|