一道华为笔试题

#include <iostream>

class human
{
public:
static int human_num;

human(){
human_num++;
std::cout<<"default human num is: "<<human_num<<std::endl;
};
human(const human& c){
std::cout<<"copy human num is: "<<human_num<<std::endl;
};


human operator=(const human& c){
std::cout<<"= human num is: "<<human_num<<std::endl;
int a = 2;
return c;
}

~human(){
human_num--;
std::cout<<"destruct human num is: "<<human_num<<std::endl;
}

void print()
{
std::cout<<"human num is: "<<human_num<<std::endl;
}


protected:
private:
};
int human::human_num = 0;
human& f1(human& x)
{
x.print();
return x;
}
int main(int argc, char* argv[])
{
human h1;
h1.print();
human h2 = f1(h1);
h2.print();
return 0;
}

//注意两点:1.函数临时返回对象就是传入的实参旳副本,直到拷贝给其他对象,再销毁这个临时对象。如果不拷贝则会立即销毁。2.在声明一个对象时如果同时赋值,则调用拷贝构造,省掉一个默认构造。这点很重要。

posted on 2015-08-24 22:08  bitbit  阅读(806)  评论(0编辑  收藏  举报