class employee
{
public:
string name;
int ID;
employee(const string & m_name):name(m_name),ID(number++) {};
static int numb() { //类外初始化
return 0;
}
private:
static int number;
};
//int employee::number = 0;
int employee::number= numb(); //静态数据成员必须在类外初始化,无论numb()这个函数是私有还是公有,
//都只要直接调用就好
struct KK
{
int *k;
KK() {
k = new int;
}
KK(int i) {
k = new int(i);
cout << 86 << endl;
};
KK(const KK &y) :k(y.k) { cout << 9 << endl; };
KK &operator=(const KK &o)
{
*k = *(o.k);
cout << 99 << endl;
return *this;
}
~KK() { cout << "析构了" << endl;
cout << *k << endl;
//delete k;
};
};
int* haha()
{
KK u(5);
return u.k;
}
KK &hh()
{
KK u(5);
cout << &u << endl;
return u;
//我觉得是这个u不见了,因为它是临时变量,出了作用域就不见了,返回得虽是个引用,
//但此时会创建一个临时变量,引用得是这个临时变量
}
void main()
{
employee a("a");
employee b("b");
cout << a.ID << endl;
cout << b.ID << endl;
//haha();
KK &uu =hh(); //这里uu调用得是拷贝构造函数,而不是复制构造函数
//并且尽管这里是引用,hh中得局部对象也会被析构
KK j(5);
int *hp= haha();
cout << *hp << endl; //此时输出得是乱码,因为haha()函数里得KK类型出了作用域就被析构了,
//从而指针也被删除了,因此这里hp指向得是一个野指针
//如果在析构函数里不delete,则这里得输出还是指向那块地址得值
}