11-C++面向对象(权限、初始化列表、默认参数、构造函数调用)

成员访问权限

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

  •         public:公共的,任何地方都可以访问(struct默认)
  •         protected:子类内部、当前类内部可以访问
  •         private:私有的,只有当前类内部可以访问(class默认)

        子类内部访问父类成员的权限,是以下两项种权限最小的那个:

  •         成员本身的访问权限
  •         上一级父类的继承方式

        开发中用的最多的继承方式是public,这样能保留父类原来的成员访问权限

        访问权限不影响对象的内存布局 

初始化列表

        一种便捷的初始化成员变量的方式

#include<iostream>
using namespace std;
struct Person
{
	int m_age;
	int m_height;
	/*Person(int age, int height) {
		m_age = age;
		m_height = height;
	}*/
	Person(int age, int height) :m_age(age), m_height(height) {

	}
};
int main() {
	Person person(18, 180);
	return 0;
}

只能在构造函数种使用

初始化顺序只跟成员变量的声明顺序有关 

初始化列表与默认参数配合使用

//分开写,默认参数只能写在函数声明中
struct Car
{
	int m_age;
	int m_height;
	Car(int age = 0, int height = 0);
};
//初始化列表只能写在函数实现中
Car::Car(int age, int height) :m_age(age), m_height(height) {}

如果函数声明和实现是分离的:

  •         初始化列表只能写在函数的实现中
  •         默认参数只能写在函数的声明中

构造函数的互相调用

#include<iostream>
using namespace std;
struct Person
{
	int m_age;
	int m_height;
	Person():Person(0, 0) {
		
	}
	//Person(){
	//	//相当于创建了一个临时的Person对象
	//	Person(0, 0);
	//}
	Person(int age, int height) {
		m_age = age;
		m_height = height;
	}
};
int main() {
	Person person;
	cout << person.m_age << endl;
	cout << person.m_height << endl;
	return 0;
}

父类的构造函数

  •         子类的构造函数默认会调用父类的无参构造函数
  •         如果子类的构造函数显示地调用了父类的有参构造函数,就不会再去默认调用父类的无  参构造函数
  •         如果父类缺少无参构造函数,子类的构造函数必须显示调用父类的有参构造函数

猜你喜欢

转载自blog.csdn.net/qq_56728342/article/details/129627066