继承中的对象初始化列表

#include<iostream>

using namespace std;

class A
{
	protected:
	int m_a;
	public:
	A(int a);
};
A::A(int a)
{
	cout<<"AA"<<endl;
	m_a=a;
}
class C
{
	private:
	int m_c;
	public:
	C(int c);
	
};
C::C(int c)
{
	cout<<"CC"<<endl;
	m_c=c;
}
class D
{
	private:
	int m_d;
	public:
	D(int d);
};
D::D(int d)
{
	cout<<"DD"<<endl;
	m_d=d;
}
class B:public A
{
	private:
	int m_b;
	C c;
	D d;
	const int e;
	
	public:
	B(int b);
	void print();
};
B::B(int b):A(b),c(2),e(6),d(3)   //仅在此处用   父类参数 类对象成员对象  const
{
	cout<<"B"<<endl;
	m_b=b;
}
void B::print()
{
	cout<<m_a<<endl;
	cout<<m_b<<endl;
}

int main()
{
	B b(1);
	b.print();
	return 0;
}

初始化列表的三种情况

1.继承有参的类

2.当类中定义了类成员对象

3.类中定义了const型对象

猜你喜欢

转载自blog.csdn.net/qq_41916395/article/details/81263745
今日推荐