注册 登录
编程论坛 C++教室

刚学C++ 遇到个问题,求好心人解答。

xlhcy2014 发布于 2014-03-08 23:33, 394 次点击
程序代码:
#include<iostream>
using namespace std;
class num
{
public:
    num(){n=1;cout<<"默认构造函数\n";}
    num(int i){n=i;cout<<"带参数的构造函数\n";}
    num(num &a){this->n=a.n;cout<<"copy\n";}
    ~num(){cout<<"the end\n";}
    int get()const{return n;}
     num & operator ++() //这里,我本来是想按引用返回,避免产生*this的副本,但最后还是产生了,为什么加了引用都不行? 如何不创建副本或拷贝。
    {
    ++n;
    return *this;
    }
private:
    int n;
};
int main()
{
    num i;
    cout<<"i:"<<i.get()<<endl;
    num ab=++i;
    cout<<"i:"<<ab.get()<<endl;
    return 0;
}


[ 本帖最后由 xlhcy2014 于 2014-3-8 23:34 编辑 ]
1 回复
#2
rjsp2014-03-10 08:32
这个拷贝构造发生在 构造ab 时,和 ++i 屁关系都没有
不信你可以将 num ab=++i; 改为 num ab = i; 试试

1