24小时热门版块排行榜    

查看: 1007  |  回复: 3

我爱小虫子

新虫 (正式写手)

[求助] c++关于vector和拷贝构造函数 ,输出不理解

一道c++小程序,输出不理解为什么调用了两次
copy construct ,
完整程序如下:(显示头像的地方是右括号)
#include<iostream>
#include<vector>
using namespace std;

class Demo{
public:
         char *str;
    Demo():str(NULL)
    {  cout<<"default construct!"<<endl;
        }

         Demo(const Demo &d)
         {
                 cout<<"copy construct"<<endl;
                 this->str=new char[strlen(d.str)+1];
                 strcpy(this->str,d.str);
         }


         ~Demo()
         {
                 if(str)
                 {       
                         cout<<"~Demo"<<endl;
                         delete []str;       
                 }
         }
       
       
};

int main()
{
        Demo d1;
        d1.str=new char[32];
        strcpy(d1.str,"zhong guo";
    cout<<d1.str<<endl;

        vector<Demo> *a1=new vector<Demo>();       
        cout<<"1"<<endl;
        a1->push_back(d1);
   
        cout<<(a1->front()).str<<endl;
       

        delete a1;
}

运行结果如下图:

c++关于vector和拷贝构造函数 ,输出不理解
1.jpg
回复此楼

» 猜你喜欢

» 本主题相关价值贴推荐,对您同样有帮助:

已阅   回复此楼   关注TA 给TA发消息 送TA红花 TA的回帖

libralibra

至尊木虫 (著名写手)

骠骑将军

什么编译器?
我的vs2008,只有一次
c++关于vector和拷贝构造函数 ,输出不理解-1
matlab/VB/python/c++/Java写程序请发QQ邮件:790404545@qq.com
2楼2014-04-10 23:59:01
已阅   回复此楼   关注TA 给TA发消息 送TA红花 TA的回帖

我爱小虫子

新虫 (正式写手)

引用回帖:
2楼: Originally posted by libralibra at 2014-04-10 23:59:01
什么编译器?
我的vs2008,只有一次

我用的VS2005
3楼2014-04-11 07:43:16
已阅   回复此楼   关注TA 给TA发消息 送TA红花 TA的回帖

我爱小虫子

新虫 (正式写手)

引用回帖:
2楼: Originally posted by libralibra at 2014-04-10 23:59:01
什么编译器?
我的vs2008,只有一次

刚试了下,用VC6.0运行结果跟你的也是一样的。。
4楼2014-04-11 07:59:07
已阅   回复此楼   关注TA 给TA发消息 送TA红花 TA的回帖
相关版块跳转 我要订阅楼主 我爱小虫子 的主题更新
信息提示
请填处理意见