面向对象程序设计 阅读程序并给出正确的结果

【EG1】考察析构函数调用顺序

#include<iostream>
using namespace std;
class test
{
public:
	test(int a)
	{
		x=a;cout<<x<<endl;
	}
	test(test &s)
	{
		x=s.x;cout<<x<<endl;
	}
	void setx(int a)
	{
		x=a;
	}
	~test()
	{
		cout<<x<<endl;
	}
private:
	int x;
};
int main()
{
	test p1(1),p2(p1);
	p2.setx(2);
	test p3=p2;
} 

【AS1】

步骤1:调用变换构造函数,给p1赋值,同时输出p1.x=1
步骤2:调用复制构造函数,给p2赋值,同时输出p2.x=p1.x=1
步骤3:调用成员函数修改p2.x的值,p2.x=2
步骤4:调用复制构造函数,给p3赋值,p3.x=p2.x=2
步骤5:main函数调用结束,释放所有对象空间,自动调用析构函数依次释放p3,p2,p1,同时输出p3.x=2,p2.x=2,p1.x=1
(析构函数是对象被释放时自动调用的)

控制台显示的结果:
1
1
2
2
2
1

【EG2】考察复制构造函数调用顺序

#include<iostream>
using namespace std;
class test
{
    int x;
public:
    test()
    {

    }
    test(int a)
    {
        x=a;
    }
    test(test &s)
    {
        x=s.x;
        cout<<"Copy constructor"<<endl;
    }
    void disp()
    {
        cout<<x++<<endl;
    }
};
test func(test s)
{
    s.disp();
    return s;
}
int main()
{
    test a1(2),a2(a1),a;
    a1.disp();
    a2.disp();
    a=func(a1);
    func(a2);
    a.disp();
    a1.disp();
    a2.disp();
    return 0;
}

【AS2】

步骤1:调用变换构造函数,给a1赋值,a1.x=2
步骤2:调用复制构造函数,给a2赋值,a2.x=a1.x=2,输出Copy constructor
步骤3:输出a1.x=2,同时a1.x++=3
步骤3:输出a2.x=2,同时a2.x++=3
步骤4:实参a1赋值给形参s,调用复制构造函数,输出Copy constructor
步骤5:进入func函数,输出s.x=a1.x=3,同时s.x++=4
步骤6:返回s时调用复制构造函数,输出Copy constructor,同时a.x=s.x=4
步骤7:实参a2赋值给形参s,调用复制构造函数,输出Copy constructor
步骤8:进入func函数,输出s.x=a2.x=3
步骤9:返回s时调用赋值构造函数,输出Copy constructor
步骤10:输出a.x=4
步骤11:输出a1.x=3
步骤12:输出a2.x=3

控制台显示的结果:
Copy constructor
2
2
Copy constructor
3
Copy constructor
Copy constructor
3
Copy constructor
4
3
3

【EG3】考察类的嵌套定义、析构函数调用顺序

#include<iostream>
using namespace std;
class A
{
public:
    A(int i){cout<<"AC"<<endl;}
    ~A(){cout<<"AD"<<endl;}
};
class B
{
public:
    B(int i){cout<<"BC"<<endl;}
    ~B(){cout<<"BD"<<endl;}
};
class C
{
public:
    C(int i):a(i),b(i)
    {
        cout<<"CC"<<endl;
    }
    ~C(){cout<<"CD"<<endl;}
private:
    B b;A a;
};
int main()
{
    int i=0;
    C c(i);
}

【AS3】

步骤1:调用类B的构造函数,输出BC
步骤2:调用类A的构造函数,输出AC
步骤3:调用类C的构造函数,输出CC
步骤4:调用类C的析构函数,输出CD
步骤5:调用类A的析构函数,输出AD
步骤6:调用类B的析构函数,输出BD

控制台显示的结果:
BC
AC
CC
CD
AD
BD

【EG4】考察析构函数

#include<iostream>
using namespace std;
class test
{
public:
	test()
	{
		cout<<"Allocating memory!"<<endl;
	}
	~test()
	{
		cout<<"Dellocating memory!"<<endl;
	}
};
int main()
{
	cout<<"I am sure the memory is enough!"<<endl;
	{
		test x;
	}
	cout<<"What do you think of our memory service"<<endl;
} 

【AS4】

对象调用的方式不同,该程序定义对象结束后随机释放对象

控制台显示的结果:
I am sure the memory is enough!
Allocating memory!
Dellocating  memory!
What do you think of our memory service
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值