c++结构体

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;
}

virtual void lifestyle(){
cout<<"eating rotten corpse"<<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 lifestyle(){
cout<<"lifestyle:eating plants or anmials"<<endl;
}

void display(){
prop();
bel();
// species(); // error: ‘void Biological::species()’ is private
}
};

struct Plant:private Biological{
public:
void lifestyle(){
cout<<"lifestyle:By inorganic matter"<<endl;
}

void display(){
prop();
bel();
//species(); // error: ‘void Biological::species()’ is private
}
};

struct Both:protected Biological{ // 私有继承
public:
void lifestyle(){
cout<<"lifestyle:both with Biological"<<endl;
}

void display(){
prop();
bel();
//species(); // error: ‘void Biological::species()’ is private
}
};

void animalDis(){
Animal animal;
animal.display();
animal.lifestyle();
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.lifestyle();
// 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.lifestyle();
// 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;
}

 

posted @ 2019-09-04 11:35  hiligei  阅读(302)  评论(0编辑  收藏  举报