鱼C论坛

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

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

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

protected的访问类别:这个类及其子类;
#include <iostream>
#include <string>

class Animal
{
public:
    Animal(std::string theName);
    void eat();
    void eat(int num);

protected:
    std::string name;
};

class Pig : public Animal
{
public:
    Pig(std::string theName);
    void climb();
};

Animal::Animal(std::string theName)
{
    name = theName;
}

void Animal::eat()
{
    std::cout << "I'm eatting!" << std::endl;
}

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

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

Pig::Pig(std::string theName) : Animal(theName)
{
}

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


int main()
{
    Pig pig("小猪猪");

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

    pig.eat();
    pig.eat(15);
    pig.climb();

    return 0;
}
问题主要在:
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,只能写一个函数吗??
比如
std::string pig::get_name(){
    return name;
}

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

使用道具 举报

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

使用道具 举报

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

本版积分规则

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

GMT+8, 2024-10-3 21:19

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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