车大大一下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;
}