构造函数初始化列表
#include "stdafx.h"
#include <iostream>
#include<math.h>
using namespace std;
class A {
public:
A(int a)
{
m_a = a;
}
void printfa()
{
cout << "A" << m_a << endl;
}
private:
int m_a;
};
class B {
public:
B(A &a1, A&a2, int b) :m_a1(a1), m_a2(a2)
{
m_b = b;
}
B(int a1, int a2, int b) :m_a1(a1), m_a2(a2)
{
m_b = b;
}
void printfb()
{
cout << "B" << m_b << endl;
}
~B() {
cout << "B析构" <<m_b<< endl;
m_a1.printfa();
m_a2.printfa();
}
private:
int m_b;
A m_a1;
A m_a2;
};
void test1()
{
A a1(10);
A a2(20);
B b1(a1, a2, 100);
b1.printfb();
}
int main()
{
B b(10, 20, 30);
b.printfb();
return 0;
}
练习
#include "stdafx.h"
#include <iostream>
#include<math.h>
using namespace std;
class ABCD {
public:
ABCD(int a, int b, int c)
{
m_a = a;
m_b = b;
m_c = c;
cout << "a=" << a << "b=" << b << "c=" << c << endl;
}
~ABCD()
{
cout << "ABCD析构" << endl;
}
int geta()
{
return m_a;
}
private:
int m_a;
int m_b;
int m_c;
};
class me {
public:
me() :abcd1(1, 2, 3), abcd2(4, 5, 6), m(100)
{
cout << "me()" << endl;
}
~me()
{
cout << "me析构" << endl;
}
me(const me&obj) :abcd1(7, 8, 9), abcd2(10, 11, 12), m(100)
{
cout << "me const" << endl;
}
ABCD func()
{
return abcd1;
}
private:
ABCD abcd1;
ABCD abcd2;
const int m;
};
void dothing(me mm)
{
cout << "dothing" << mm.func().geta() << endl;
}
int run()
{
me m;
dothing(m);
return 0;
}
int run2()
{
cout << "run2 start" << endl;
ABCD aaa= ABCD(400, 500, 600);
cout << "run2 endl" << endl;
return 0;
}
int main()
{
run2();
return 0;
}
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/6bcd845847c66377f3bda0c9483c51cb.png)
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/1cc5f68630d615f4b2cddbb5165d0910.png)
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/4f87e43cf66f427847db4c9aaa3ad6aa.png)