vs2008中运行一个在派生类中引用保护成员的程序,error C2248: “Student:num”: 无法访问 protected成员函数,该怎么处理
vs2008中运行一个在派生类中引用保护成员的程序,error C2248: “Student::num”: 无法访问 protected成员函数
#include "stdafx.h"
#include<iostream>
#include<string>
using namespace std;
class Student
{public:
void display()
{cout<<"num:"<<num<<endl;
cout<<"name:"<<name<<endl;
cout<<"sex:"<<sex<<endl;}
protected:
int num;
string name;
char sex;
};
class Student1:protected Student
{public:
void display1()
{cout<<"num:"<<num<<endl;
cout<<"name:"<<name<<endl;
cout<<"sex:"<<sex<<endl;
cout<<"age:"<<age<<endl;
cout<<"address:"<<addr<<endl;}
private:
int age;
string addr;
};
int main()
{Student1 stud1;
stud1.display1();
stud1.num=10023;
return 0;
}
------解决方案--------------------
stud1.num=10023; //num是Student类的protected成员,不能直接使用对象访问,
要想用子类的对象访问必须把Student类的num改为public成员,Student1的继承方式也改为public
------解决方案--------------------
#include "stdafx.h"
#include<iostream>
#include<string>
using namespace std;
class Student
{public:
void display()
{cout<<"num:"<<num<<endl;
cout<<"name:"<<name<<endl;
cout<<"sex:"<<sex<<endl;}
protected:
int num;
string name;
char sex;
};
class Student1:protected Student
{public:
void display1()
{cout<<"num:"<<num<<endl;
cout<<"name:"<<name<<endl;
cout<<"sex:"<<sex<<endl;
cout<<"age:"<<age<<endl;
cout<<"address:"<<addr<<endl;}
private:
int age;
string addr;
};
int main()
{Student1 stud1;
stud1.display1();
stud1.num=10023;
return 0;
}
------解决方案--------------------
stud1.num=10023; //num是Student类的protected成员,不能直接使用对象访问,
要想用子类的对象访问必须把Student类的num改为public成员,Student1的继承方式也改为public
------解决方案--------------------