鱼C论坛

 找回密码
 立即注册
查看: 1060|回复: 1

[已解决]访问控制问题

[复制链接]
发表于 2020-3-23 20:23:05 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
各位大神们看完Animal类的定义直接看main函数就好了,中间的不重要
  1. #include<iostream>       
  2. #include<string>
  3. class Animal
  4. {
  5. public:
  6.         std::string mouth;

  7.         Animal(std::string  theName);
  8.         void eat();
  9.         void sleep();
  10.         void drool();

  11. protected:
  12. std::string name;
  13. };
  14. class Pig:public Animal
  15. {
  16. public:
  17.         void climb();
  18.         Pig(std::string  theName);
  19. };
  20. class Turtle:public Animal
  21. {
  22. public:
  23.         void swim();
  24.         Turtle(std::string  theName);
  25. };
  26. Animal::Animal(std::string  theName)
  27. {
  28.         name = theName;
  29. }
  30. void Animal::eat()
  31. {
  32.         std::cout<<”I am eating!”<<std::endl;
  33. }
  34. void Animal::sleep()
  35. {
  36.         std::cout<<”I am sleeping!”<< std::endl;
  37. }
  38. void Animal::drool()
  39. {
  40.         std::cout<<”I am drooling!”<< std::endl;
  41. }
  42. Pig::Pig(std::string  theName):Animal(theName)
  43. {
  44. }
  45. void Pig::climb()
  46. {
  47.         std::cout<<”I am climbing!”<< std::endl;
  48. }
  49. Turtle::Turtle(std::string  theName):Animal(theName)
  50. {
  51. }
  52. void Turtle::swim()
  53. {
  54.         std::cout<<”I am swimming!”<< std::endl;
  55. }


  56. int main()
  57. {
  58.         Pig pig(“小猪猪”);  
  59.         Turtle turtle(“小甲鱼”);
  60.         std::cout<<”这只猪的名字是:”<<pig.name<<std::endl;
  61.         std::cout<<”这只乌龟的名字是:”<<turtle.name<<std::endl;
  62.         pig.eat();
  63.         turtle.eat();
  64.         pig.climb();
  65.         turtle.swim();
  66.         return 0;
  67. }
复制代码

在代码中对std::string name;使用了protected访问控制,也就是说只有Animal类和它的子类可以对name进行访问
那么为什么在main函数中对pig和turtle的名字进行打印时系统会报错?
pig是,Animal的子类Pig,的对象,难道子类的对象就不能访问基类的protected元素吗
请大神赐教
最佳答案
2020-3-23 20:29:50
private: 只能由该类中的函数、其友元函数访问,不能被任何其他访问,该类的对象也不能访问.
protected: 可以被该类中的函数、子类的函数、以及其友元函数访问,但不能被该类的对象访问
public: 可以被该类中的函数、子类的函数、其友元函数访问,也可以由该类的对象访问
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2020-3-23 20:29:50 | 显示全部楼层    本楼为最佳答案   
private: 只能由该类中的函数、其友元函数访问,不能被任何其他访问,该类的对象也不能访问.
protected: 可以被该类中的函数、子类的函数、以及其友元函数访问,但不能被该类的对象访问
public: 可以被该类中的函数、子类的函数、其友元函数访问,也可以由该类的对象访问
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-7-13 04:11

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表