![]() |
#2
specilize2011-09-25 16:51
|
只有本站会员才能查看附件,请 登录
在学习C++ Primer 5第14章私有继承时,student类的代码在VC6下编译出现“error C2614: 'Student ' : illegal member initialization: 'string ' is not a base or member ”,后将头文件中用了using namespace std; 然后去掉所有的std::,就没这个问题了。
但是接着在友元重载“<<”时,提示“”error C2248: 'arr_out' : cannot access private member declared in class 'Student',这个arr_out成员函数是私有成员,但是重载函数已经声明为友元了,应该可以访问才对。(将arr_out设置成公有成员后,可以成功编译。)
然后我接着定义一个测试的友元函数,它可以正常访问arr_out私有成员函数。
1.studnet .h 头文件,类声明

#include <iostream>
#include <valarray>
#include <string>
using namespace std; //增加的语句
类声明中arr_out私有成员部分
class Student : private string, private valarray<double>
{
private:
typedef valarray<double> ArrayDb;
// private method for scores output
ostream & arr_out(ostream & os) const; //arr_out私有成员函数
……//省略其他部分
// output
friend ostream & operator << (ostream & os,
const Student & stu); //友元重载<<,实现中访问arr_out
friend ostream & test(ostream & os,const Student & stu); //测试友元函数
}
#include <valarray>
#include <string>
using namespace std; //增加的语句
类声明中arr_out私有成员部分
class Student : private string, private valarray<double>
{
private:
typedef valarray<double> ArrayDb;
// private method for scores output
ostream & arr_out(ostream & os) const; //arr_out私有成员函数
……//省略其他部分
// output
friend ostream & operator << (ostream & os,
const Student & stu); //友元重载<<,实现中访问arr_out
friend ostream & test(ostream & os,const Student & stu); //测试友元函数
}
2.student.cpp 类实现文件

// private method
ostream & Student::arr_out(ostream & os) const
{
int i;
int lim = ArrayDb::size();
if (lim > 0)
{
for (i = 0; i < lim; i++)
{
os << ArrayDb::operator[](i) << " ";
if (i % 5 == 4)
os << endl;
}
if (i % 5 != 0)
os << endl;
}
else
os << " empty array ";
return os;
}
……//省略其他部分
// use string version of operator<<()
ostream & operator << (ostream & os, const Student & stu)
{
os << "Scores for " << (const string &) stu << ":\n";
stu.arr_out(os); // use private method for scores 无法访问arr_out私有成员
return os;
}
//测试友元函数是否能访问私有成员
ostream & test(ostream & os,const Student &stu)
{
os << "Scores for " << (const string &) stu << ":\n";
stu.arr_out(os); // use private method for scores
return os;
}
3.附件是修改后的问题代码和书本源代码(在vc上也是有问题的)
搞了好长时间,还是想不通,很是纠结,故贴上来,特来求教。
[ 本帖最后由 梦桐云轩 于 2011-9-25 16:38 编辑 ]