C++ 中关键字struct和class都是用来定义类的,二者除了默认访问限定符不同,其他所有方面都一样。故以下把类和结构体统称类。
class的默认权限为private,而struct的默认权限为public。
class默认继承为private,struct默认继承问public。
struct和class一样支持继承、多态、构造、析构、public、private、protect三个关键字、支持成员函数。
#include<iostream> #include<cstdio> using namespace std; struct Biological{ public: string property; virtual void prop(){ cin>>property; cout<<"property:"<<property<<endl; } private: // c++默认权限为private string name; void species(){ cin>>name; cout<<"name:"<<name<<endl; } protected: string belong; void bel(){ cin>>belong; cout<<"belong:"<<belong<<endl; } }; struct Animal:public Biological{// 公有继承为默认可以省略 public: void display(){ prop(); bel(); // species(); // error: ‘void Biological::species()’ is private } }; struct Plant:private Biological{ public: void display(){ prop(); bel(); //species(); // error: ‘void Biological::species()’ is private } }; struct Both:protected Biological{ // 私有继承 public: void display(){ prop(); bel(); //species(); // error: ‘void Biological::species()’ is private } }; void animalDis(){ Animal animal; animal.display(); animal.property="cat"; cout<<"修改animal.property为:"<<animal.property<<endl; // animal.name="xiaohei"; // error: ‘std::__cxx11::string Biological::name’ is private // cout<<"animal.name"<<animal.name<<endl; // animal.belong="animal"; // error: ‘std::__cxx11::string Biological::belong’ is protected // cout<<"animal.belong"<<animal.belong<<endl; } void plantDis(){ Plant plant; plant.display(); // plant.property="tree"; // error: ‘std::__cxx11::string Biological::property’ is inaccessible // cout<<"修改plant.property为:"<<plant.property<<endl; // plant.name="poplar"; //error: ‘std::__cxx11::string Biological::name’ is private // cout<<"修改plant.name为:"<<plant.name<<endl; // plant.belong="plant"; //error: ‘std::__cxx11::string Biological::belong’ is protected // cout<<"修改plant.belong为:"<<plant.belong<<endl; } void bothDis(){ Both both; both.display(); // both.property="tree"; // error: ‘std::__cxx11::string Biological::property’ is inaccessible // cout<<"修改both.property为:"<<both.property<<endl; // both.name="poplar"; // error: ‘std::__cxx11::string Biological::name’ is private // cout<<"修改both.name为:"<<both.name<<endl; // both.belong="plant"; // error: ‘std::__cxx11::string Biological::belong’ is protected // cout<<"修改both.belong为:"<<both.belong<<endl; } int main(){ animalDis(); plantDis(); bothDis(); return 0; }
原文:https://www.cnblogs.com/ligei/p/11458058.html