//这是我看书上的例题改的,原来的程序没有重载>>,没有数据输入函数;
//我改了后问题就出来了....我>>函数居然不能访问类里的数据成员,至少出错提示是这么说的"cannot access......"
//编译器VC6.0
#include <iostream>
#include <string>
using namespace std;
class Student //声明基类
{
public: //基类公用成员
void display( );
friend istream& operator >>(istream& in,Student& stu);
protected : //基类保护成员
int num;
string name;
char sex;
};
void Student::display( )
{
cout<<"num: "<<num<<endl;
cout<<"name: "<<name<<endl;
cout<<"sex: "<<sex<<endl;
}
istream& operator >>(istream& in,Student& stu)
{
cout<<"Please input the num,name,and sex: \n";
in>>stu.num>>stu.name>>stu.sex;
return in;
}
class Student1: protected Student //用protected继承方式声明一个派生类
{
public:
void display1( );
friend istream& operator >>(istream& in,Student1& stu);//这里该过来了,谢谢楼下提醒,不过错误提示还是没变;
private:
int age;
string addr;
};
void Student1::display1( )
{
cout<<"num: "<<num<<endl; //引用基类的保护成员
cout<<"name: "<<name<<endl;
cout<<"sex: "<<sex<<endl;
cout<<"age: "<<age<<endl; //引用派生类的私有成员
cout<<"address: "<<addr<<endl;
}
istream& operator >>(istream& in,Student1& stu)
{
cout<<"Please input the num,name,sex,age,and address:\n";
in>>stu.num>>stu.name>>stu.sex>>stu.age>>stu.addr;
return in;
}
int main( )
{
Student1 stud1; //stud1是派生类student1的对象
cout<<"input the student's record:\n";
cin>>stud1;
stud1.display1( ); //display是派生类中的公用成员函数
return 0;
}
--------------------------------------传说中的分割线-------------------------------------------
这里的错误提示:
Compiling...
C5-3.CPP
E:\C++源代码\教材例题程序\C5\C5-3.CPP(25) : error C2248: 'num' : cannot access protected member declared in class 'Student'
E:\C++源代码\教材例题程序\C5\C5-3.CPP(10) : see declaration of 'num'
E:\C++源代码\教材例题程序\C5\C5-3.CPP(25) : error C2248: 'name' : cannot access protected member declared in class 'Student'
E:\C++源代码\教材例题程序\C5\C5-3.CPP(11) : see declaration of 'name'
E:\C++源代码\教材例题程序\C5\C5-3.CPP(25) : error C2248: 'sex' : cannot access protected member declared in class 'Student'
E:\C++源代码\教材例题程序\C5\C5-3.CPP(12) : see declaration of 'sex'
E:\C++源代码\教材例题程序\C5\C5-3.CPP(50) : error C2248: 'num' : cannot access protected member declared in class 'Student'
E:\C++源代码\教材例题程序\C5\C5-3.CPP(10) : see declaration of 'num'
E:\C++源代码\教材例题程序\C5\C5-3.CPP(50) : error C2248: 'name' : cannot access protected member declared in class 'Student'
E:\C++源代码\教材例题程序\C5\C5-3.CPP(11) : see declaration of 'name'
E:\C++源代码\教材例题程序\C5\C5-3.CPP(50) : error C2248: 'sex' : cannot access protected member declared in class 'Student'
E:\C++源代码\教材例题程序\C5\C5-3.CPP(12) : see declaration of 'sex'
E:\C++源代码\教材例题程序\C5\C5-3.CPP(50) : error C2248: 'age' : cannot access private member declared in class 'Student1'
E:\C++源代码\教材例题程序\C5\C5-3.CPP(35) : see declaration of 'age'
E:\C++源代码\教材例题程序\C5\C5-3.CPP(50) : error C2248: 'addr' : cannot access private member declared in class 'Student1'
E:\C++源代码\教材例题程序\C5\C5-3.CPP(36) : see declaration of 'addr'
执行 cl.exe 时出错.
C5-3.OBJ - 1 error(s), 0 warning(s)
谁告诉一下怎么错了?还有,对代码有什么意见都说出来哈,
[此贴子已经被作者于2006-12-6 18:23:21编辑过]