鱼C论坛

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

protected 子类为什么不能访问??

[复制链接]
发表于 2019-6-16 15:08:42 | 显示全部楼层 |阅读模式
5鱼币
本帖最后由 方大侠 于 2019-6-16 17:02 编辑

protected的访问类别:这个类及其子类;

  1. #include <iostream>
  2. #include <string>

  3. class Animal
  4. {
  5. public:
  6.     Animal(std::string theName);
  7.     void eat();
  8.     void eat(int num);

  9. protected:
  10.     std::string name;
  11. };

  12. class Pig : public Animal
  13. {
  14. public:
  15.     Pig(std::string theName);
  16.     void climb();
  17. };

  18. Animal::Animal(std::string theName)
  19. {
  20.     name = theName;
  21. }

  22. void Animal::eat()
  23. {
  24.     std::cout << "I'm eatting!" << std::endl;
  25. }

  26. void Animal::eat(int num)  //eat()函数重载
  27. {
  28.     std::cout << "I'm eatting" << num << "碗混沌" << std::endl;
  29. }

  30. void Animal::sleep()
  31. {
  32.     std::cout << "I'm sleeping!Don't disturb me!\n" << std::endl;
  33. }
  34. void Animal::drool()
  35. {
  36.     std::cout << "我是公的,看到母的我会流口水,我正在流口水。。。\n" << std::endl;
  37. }

  38. Pig::Pig(std::string theName) : Animal(theName)
  39. {
  40. }

  41. void Pig::climb()
  42. {
  43.     std::cout << "我是一个只漂亮的小母猪猪,我会上树,我正在爬树,嘘。。。\n" << std::endl;
  44. }


  45. int main()
  46. {
  47.     Pig pig("小猪猪");

  48.     std::cout << "这只猪的名字是: " << pig.name << std::endl;                // 错误

  49.     pig.eat();
  50.     pig.eat(15);
  51.     pig.climb();

  52.     return 0;
  53. }

复制代码

问题主要在:
std::cout << "这只猪的名字是: " << pig.name << std::endl;                // 编译错误

3.cpp:87:51: error: 'name' is a protected member of 'Animal'
    std::cout << "这只猪的名字是: " << pig.name << std::endl...
                                           ^
3.cpp:14:17: note: declared protected here
    std::string name;
                ^
1 error generated.
因为是protected,所以子类不能访问???
要输出名字name,只能写一个函数吗??
比如
  1. std::string pig::get_name(){
  2.     return name;
  3. }
复制代码

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2019-6-16 15:30:34 | 显示全部楼层
对的只有public可以直接访问,protected和private都不可通过外部直接访问成员。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

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

本版积分规则

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

GMT+8, 2024-5-5 07:29

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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