本帖最后由 方大侠 于 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;
}
|