访问修饰符
Private
是访问的默认设置,正如其中的名字而言,私密,所以在类外部是无法访问的,包括子类也是无法继承的,
class Dog:public Animal
{
Dog();
Dog(string name, int age, int num_limbs);
};
//下面中的Dog dog就不能成功的访问
int main()
{
Dog dog("lucky",4,5);//dog 函数是不可访问的函数
system("pause");
}
Public
允许进行类外访问,加上后下面的dog函数就不会报错了,他可以在任何位置访问
class Dog:public Animal
{
public:
Dog();
Dog(string name, int age, int num_limbs);
};
//下面中的Dog dog就不能成功的访问
int main()
{
Dog dog("lucky",4,5);//dog 函数是不可访问的函数
system("pause");
}
Protected
只能同一类之中访问,即protected变量和函数可以从类内部以及派生(或子类)内部访问,父类中的函数,变量只能从本身或者子类来访问,不能从外部访问。
class Animal
{
protected:
Animal();
Animal(string name,int age,int num_limbs);
string Name;
int Age;
int Number0fLimbs;
void Report();
};
//继承之后的Dog类中,protected:下的Name Age Number0fLimbs也是protected类
class Dog:public Animal
{
Dog();
Dog(string name, int age, int num_limbs);
};
利用getter和setter访问Private
利用getter和setter可以在不修改访问修饰符的情况下访问Private的内部函数
下面是没有使用getter和setter时
class Creature
{
public:
Creature();
private:
float Health;
string Name;
};
int mian()
{
Creature Igor;
Igor.Name = "Igor"
system("pause");
}
Creature::Creature()
{
cout << "生物已经生成" << endl;
}
使用时
#include <iostream>
#include <string>
using namespace std;
class Creature
{
public:
Creature();
void SetName(string name);
string GetName();
private:
float Health;
string Name;
};
int mian()
{
Creature Igor;
Igor.SetName("LUCKY");//利用set设置名字
Igor.GetName();//利用get返回名字
system("pause");
}
Creature::Creature()
{
cout << "生物已经生成" << endl;
}
void Creature::SetName(string name)//setter 因为其本身就时在类中,可以访问private中的数据,又因为在public中所以可以被类外访问
{
Name = name;
}
string Creature::GetName() //getter 因为其本身就时在类中,可以访问private中的数据,又因为在public中所以可以被类外访问
{
return Name;
}
继承访问符设置
class Creature
{
public:
Creature();
void SetName(string name);
string GetName();
private:
float Health;
string Name;
};
class dog : public Creature// dog将继承来的特征设为public,即可以外部访问
{
}
class cat : private Creature//cat将继承来的特征设为private,只能从类里面访问
{
}
class igor : protected Creature//igor将继承来的特征设为protected,可以再次继承
{
}
参考视频:
https://www.bilibili.com/video/BV1Dd4y1R7VS/?p=55&spm_id_from=pageDriver&vd_source=201eb8bc288ccc360992decc66897866