|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
各位大神们看完Animal类的定义直接看main函数就好了,中间的不重要
- #include<iostream>
- #include<string>
- class Animal
- {
- public:
- std::string mouth;
- Animal(std::string theName);
- void eat();
- void sleep();
- void drool();
- protected:
- std::string name;
- };
- class Pig:public Animal
- {
- public:
- void climb();
- Pig(std::string theName);
- };
- class Turtle:public Animal
- {
- public:
- void swim();
- Turtle(std::string theName);
- };
- Animal::Animal(std::string theName)
- {
- name = theName;
- }
- void Animal::eat()
- {
- std::cout<<”I am eating!”<<std::endl;
- }
- void Animal::sleep()
- {
- std::cout<<”I am sleeping!”<< std::endl;
- }
- void Animal::drool()
- {
- std::cout<<”I am drooling!”<< std::endl;
- }
- Pig::Pig(std::string theName):Animal(theName)
- {
- }
- void Pig::climb()
- {
- std::cout<<”I am climbing!”<< std::endl;
- }
- Turtle::Turtle(std::string theName):Animal(theName)
- {
- }
- void Turtle::swim()
- {
- std::cout<<”I am swimming!”<< std::endl;
- }
- int main()
- {
- Pig pig(“小猪猪”);
- Turtle turtle(“小甲鱼”);
- std::cout<<”这只猪的名字是:”<<pig.name<<std::endl;
- std::cout<<”这只乌龟的名字是:”<<turtle.name<<std::endl;
- pig.eat();
- turtle.eat();
- pig.climb();
- turtle.swim();
- return 0;
- }
复制代码
在代码中对std::string name;使用了protected访问控制,也就是说只有Animal类和它的子类可以对name进行访问
那么为什么在main函数中对pig和turtle的名字进行打印时系统会报错?
pig是,Animal的子类Pig,的对象,难道子类的对象就不能访问基类的protected元素吗
请大神赐教
private: 只能由该类中的函数、其友元函数访问,不能被任何其他访问,该类的对象也不能访问.
protected: 可以被该类中的函数、子类的函数、以及其友元函数访问,但不能被该类的对象访问
public: 可以被该类中的函数、子类的函数、其友元函数访问,也可以由该类的对象访问
|
|