为什么不复制构造函数被调用 [英] Why doesnt copy constructer get called

查看:81
本文介绍了为什么不复制构造函数被调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在语句strin z = x + y中应该调用复制构造函数....因为x + y返回一个字符串。上面的语句应该调用copy constructer ....但是它没有被调用....我错过了关于复制建设者的一些概念



我尝试过:



in the statement strin z=x+y the copy constructer should be called ....since x+y returns a string .the above statment should invoke copy constructer....but its not called....have i missed some concept about copy constructer

What I have tried:

#include <iostream>
#include<string.h>

using namespace std;
class strin
{
    int len;
    char *p;
    public:
        strin(){len=0;p=NULL;}
        strin( const char *s){cout<<"cons is called\n";
            len=strlen(s);
            p=new char[len+1];
            strcpy(p,s);



        }

         strin( const strin &s)
        {
            len=s.len;
            p=new char[len+1];
            strcpy(p,s.p);
        }

        ~strin()
        {
            delete p;
            cout<<"des is called\n";


        }


    strin operator +( const strin  &obj )
    {
        strin temp;
        temp.len =obj.len+len;
        temp.p=new char[temp.len];
        strcpy(temp.p,p);
        strcat(temp.p,obj.p);
        return temp;
        cout<<"opr is called"<<"\n";
    }
    void print(void)
    {
        cout<<p<<"\n";

    }

};
int main()
{


strin x="hello";

strin y="bob";
strin z=x+y;

z.print();

}

推荐答案

复制构造函数将在预期的位置调用,即:



The copy constructor will be called at the expected Location which is:

strin operator +( const strin  &obj )
    {
        strin temp;
        temp.len =obj.len+len;
        temp.p=new char[temp.len];
        strcpy(temp.p,p);
        strcat(temp.p,obj.p);
        return temp;             //<<<<<<Here
    }





刚用1:1源代码测试过。你怎么检查那个复制构造函数?



请记住这是复制构造函数:



Just tested with your 1:1 source code. How do you check wheter copy constructor is called?

Please Keep in mind this is the copy constructor:

strin( const strin &s)
{
...
}






while

strin( const char *s){...}



是一个接受 char * 的构造函数





析构函数

你应该使用 delete [] p ;



[Edit2]

复制构造函数也不干净,总是让字符串变长每个副本1个;)但我认为这在当下是不可能的;)


strin operator +( const strin  &obj )
{
    // ...
    return temp;
    // This is never executed because the function has been left by the above statement
    cout<<"opr is called"<<"\n";
}


这篇关于为什么不复制构造函数被调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆