c++中的protected和private的问题

来源:百度知道 编辑:UC知道 时间:2024/05/27 16:00:17
//定义一个基类mammal
class mammal
{
public:

int getAge()const{return age;}
int getWeight()const{return weight;}

protected:
int age; //可继承

private:
int weight; //不可继承
};

//派生类cat
class cat:public mammal
{

};

int main()
{
class A;
cout<<A.getAge()<<endl //可以理解,继承了protected中的age
<<A.getWeight()<<endl; //不理解为什么这一步也可以运行,既然private成员weight不可继承,为什么A仍然可以访问一个不存在的属性???
}
int main()
{
cat A; //class改成cat

}

#include<iostream>
using namespace std;

//定义一个基类mammal
class mammal
{
public:
//…
int getAge()const{return age;}
int getWeight()const{return weight;}

protected:
int age; //可继承

private:
int weight; //不可继承
};

//派生类cat
class cat:public mammal
{

cat()
{
age=1;
////weight=2;//不能访问!!!!!!!!!!!!
/////////////////这里可以访问age,却不可以访问weight
}
};

int main()
{
cat A;
cout<<A.getAge()<<endl; //可以理解,继承了protected中的age
cout<<A.getWeight()<<endl; //不理解为什么这一步也可以运行,既然private成员weight不可继承,为什么A仍然可以访问一个不存在的属性??
/////////////////private成员weight是可以继承的!但集成类里面,是不能对它进行访问的。
/////////////////这里并不是直接访问private成员weight,而是访问public:
int getWeight()啊
/////////////////getWeight在mammal的类中,在本类中,当然可以访问本来的私有变量了。

/////////////////你应该像我上面添加的代码一样,在class cat中,对类mammal中的私有或保护变量进