车大大一下C++复习

车大大一下C++复习

其实主要把代码敲了一下,我只是个搬运工:)

1.运算符重载

	int &operator[](int index)
	{
		cout << "none const[]" << index << endl;
		if (index > 0 && index < size) return data[index];
		else exit(1);
	}
int operator[](int index)
	{
		cout << "const[]" << index << endl;
		if (index > 0 && index < size) return data[index];
		else exit(1);
	}

若是使用a[0]=1,则会调用带引用的那一种,因为要是可修改的左值

2.构造函数析构函数调用

注意在C中的private中有B的对象,需要调用B的构造函数,又因为B继承了A,所以又会调用A的构造函数

#include<iostream>
using namespace std;

class A
{
public:
	A()
	{
		num++;
	}
	virtual ~A()
	{
		num--;
	}
	static int num;
};
int A::num = 0;

class B :public A
{
public:
	B()
	{
		num++;
	}
	virtual ~B()
	{
		num--;
	}

	static int num;
};
int B::num = 0;

class C :public A
{
public:
	C()
	{
		num++;
	}
	virtual ~C()
	{
		num--;
	}

	void setTu(B& b)
	{
		btu = b;
	}
	static int num;
private:
	B btu;
};
int C::num = 0;

C c1;
B b1;

void print1(A a)
{
	cout << "A中num:(const)" << a.num << endl;
}

void print2(A& a)
{
	cout << "A中num:(none const)" << a.num << endl;
}

int main()
{
	cout<<"基类A中num:"<< A::num << endl;
	cout << "子类B中num:" << b1.num << endl;
	cout << "子类C中num:" << c1.num << endl;
	cout << endl;
	
	{
		C c2;
		B b2;
		c2.setTu(b2);
		c2.~C();
		cout << "基类A中num:" << A::num << endl;
		cout << "子类B中num:" << b1.num << endl;
		cout << "子类C中num:" << c1.num << endl;
	}
	cout << endl;
	//在括号退出时又调用了B和C的析构(本来就有一次显示的C析构)所以为1,1,0
	//若没有调用C的显示析构,则和括号内的无关
	cout << "基类A中num:" << A::num << endl;
	cout << "子类B中num:" << b1.num << endl;
	cout << "子类C中num:" << c1.num << endl;

	
	return 0;
}

3.异常

#include<iostream>
using namespace std;

class Exception : public runtime_error
{
public:
	Exception() :runtime_error("Exception:runtime_error")
	{
	cout << "exception构造" << endl;
	}
	Exception(const Exception& e ) :runtime_error("Exception:runtime_error")
	{
		cout << "Exception拷贝构造" << endl;
	}
	~Exception()
	{
		cout << "Exception析构" << endl;
	}
};


class A
{
public:
	A()
	{
		cout << "A的构造" << endl;
	}
	~A()
	{
		cout << "A的析构" << endl;
	}
};

void Func()
{
	A a;
	cout << "in Fun before throw" << endl;
	throw Exception();
	cout << "in Fun after throw" << endl;
}
int main()
{
	try
	{
		cout << "在main函数中 before Func" << endl;
		Func();
		cout << "after Func" << endl;
	}
	catch(Exception& e)
	{
		cout << e.what() << endl;
	}
	
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值