您的位置:首页 > 其它

一道华为笔试题

2015-08-24 22:08 281 查看
#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.在声明一个对象时如果同时赋值,则调用拷贝构造,省掉一个默认构造。这点很重要。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: