【问题标题】:Using C++ Copy Constructor for String Concatenation使用 C++ 复制构造函数进行字符串连接
【发布时间】:2015-08-08 15:52:17
【问题描述】:

我想知道如何在这个连接过程中调用复制构造函数。 s3=s1+s2;应该能够调用复制构造函数并将其分配给 s3。甚至可能吗? 如果是,请在这里帮助我。谢谢

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

class String
{
    char x[40];

    public:
    String() { }          // Default Constructor

    String( char s[] )
    {
        strcpy(x,s);
    }

    String( String & s )
    {
        strcpy(x,s.x );
    }

    String operator + ( String s2 )
    {
        String res;

        strcpy( res.x,x );
        strcat( res.x,s2.x);

        return(res);
    }

    friend ostream & operator << ( ostream & x,String & s );
};

ostream & operator << ( ostream & x,String & s )
{
    x<<s.x;
    return(x);
}

int main()
{
    clrscr();

    String s1="Vtu";
    String s2="Belgaum";

    String s3 = s1+ s2;      // Should invoke copy constructor to concatenate and assign

    cout<<"\n\ns1 = "<<s1;
    cout<<"\n\ns2 = "<<s2;

    cout<<"\n\ns1 + s2 = "<<s3;

    getch();
    return 0;
}

【问题讨论】:

  • s1=s2调用拷贝构造函数的方式,表达式String s3 = s1+s2;也应该能够调用复制构造函数。如果你知道怎么做,请帮忙。

标签: c++ string constructor copy concatenation


【解决方案1】:

首先定义默认构造方法

String() { x[0] = '\0'; }

至于复制构造函数,那么它应该被声明为

String( const String & );
        ^^^^^     

在这种情况下,您可以从临时对象创建新对象。

我还要定义这个构造函数 字符串(字符 s[]) { strcpy(x,s); }

以下方式

String( const char s[] )
{
    strncpy( x, s, sizeof( x ) );
    x[sizeof( x ) - 1] = '\0';
}

这个操作符也应该有第二个带有限定符 const 的参数

friend ostream & operator << ( ostream & x, const String & s );
                                            ^^^^^

【讨论】:

  • 我知道它的语法,但每次执行时,重载+ 都会启动并执行。我不能调用复制构造函数吗?这有什么好处吗? string1(const string1 &s1,const string1 &s2) { strcpy(name,strcat(s1.name,s2.name)); }
  • @user3386500 它不是复制构造函数。它是一个有两个参数的构造函数。
  • 那么如何调用参数为s1+s2的复制构造函数呢?有可能吗?
  • @user3386500 你可以简单地写 String s( s1 + s2 );因为您已经定义了串联。正如我在帖子中所展示的,参数具有限定符 const 很重要。
  • 好的,谢谢,最后一个问题,这是否意味着我不能使用 s3=s1+s2; ?要激活复制构造函数吗?
猜你喜欢
  • 2014-11-21
  • 1970-01-01
  • 1970-01-01
  • 2017-12-13
  • 2013-06-27
  • 1970-01-01
  • 2018-04-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多