当我们说“一个被保护的成员可以被任何立即派生的类访问”时,这是什么意思。 在下面的例子中,结果类可以访问get_number函数,因为它只能是访问测试类的语句。
class student
{
protected:
int roll_number;
public:
void get_number(int){ cout<< "hello"; }
void put_number(void) {cout<< "hello"; }
};
class test : public student
{
protected:
float sub1;
float sub2;
public:
void get_marks(float, float) {cout<< "hello"; roll_number = 10; }
void put_marks(void) {cout<< "hello"; cout << "roll_number = " << roll_number ; }
};
class result : public test
{
float total;
public:
void display(){cout<< "hello"; roll_number = 10; }
};
int main()
{
result student;
student.get_marks(2.2, 2.2);
student.put_marks();
return 0;
}
我根据第一个语句更改了代码,保护变量roll_number无法访问结果类?
答案 0 :(得分:2)
您已将get_number
声明为公开,因此所有课程都可以看到它。
答案 1 :(得分:0)
如果您希望class result
无法直接访问数据成员roll_number
,则需要将class test
的继承权限更改为protected
:
class test : protected student
{
};
有关详细信息,请参阅The C++ FAQ Lite: Public and Private Inheritance。更改class test
从class student
继承的方式也会影响class student
中派生的class test
中数据成员的访问方式。
继承的替代方法是class test
包含指向class student
,实例的私有指针,只要class student
不是抽象类即可。