当前位置:   article > 正文

C++面向对象(三):继承、多继承_c++的struct类继承了多个类名

c++的struct类继承了多个类名

C++面向对象(三):继承、多继承

继承

继承可以让子类拥有父类的所有成员(变量 \ 函数),提高代码的复用性

// 父类
class Person {
   
protected:
	int m_age;
public:
	void run() {
   
		cout << "Person::run()" << endl;
	}
};
// 子类 
class Student : public Person {
   
	int m_score;
public:
	void study() {
   
		m_age = 666;
		cout << "Student::study(" << m_age << ")" << endl;
	}
};
// 子类
class Worker : Person{
   
	int m_salary;
public:
	void work() {
   
		cout << "Worker::work()" << endl;
	}
};
int main() {
   
	Student student;
	student.run();
	student.study();
	getchar();
	return 0;
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41

关系描述

Student是子类(subclass,派生类)

Person是父类(superclass,超类)

C++中没有像Java、OC的基类(类的老祖宗,其他所有的类最终都会继承自它。)

  • Java:java.lang.Object
  • OC:NSObject
内存布局

父类的成员变量在前,子类的成员变量在后:

struct Person {
   
	int m_age;
};
struct Student : Person {
   
	int m_score;
};
struct GoodStudent : Student {
   
	int m_money;
};

int main() {
   
	GoodStudent lubenwei;
    // 1
	lubenwei.m_age = 6;
    // 2
	lubenwei.m_score = 66;
    // 3
	lubenwei.m_money = 666;
	getchar();
	return 0;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25


成员访问权限

成员访问权限、继承方式有3种

  • public:公共的,任何地方都可以访问(struct默认)
  • protected:子类内部、当前类内部可以访问
  • private:私有的,只有当前类内部可以访问(class默认)
class Person {
   
//公有 
public:
	int m_id;
// 保护
protected:
// 私有
    int m_age;
private:
    int m_height;
};

// 继承方式
class Student : public Person {
   
	int
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/714736
推荐阅读
相关标签
  

闽ICP备14008679号