用C++复制构造函数实现字符串连接

e7arh2l6  于 2023-01-03  发布在  其他
关注(0)|答案(2)|浏览(195)

我想知道如何在这个连接过程中调用复制构造函数。我应该能够调用复制构造函数并将其赋值给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;
}
ckocjqey

ckocjqey1#

首先定义默认的构造函数

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

至于复制构造函数,则应声明为

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

在这种情况下,可以从临时对象创建新对象。
我也会定义这个构造函数String(char 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 );
                                            ^^^^^
dtcbnfnu

dtcbnfnu2#

#include <iostream>
#include <string>
using namespace std;

class String {
 private:
  string str;

 public:
  String(string str) {
    this->str = str;
  }

  String(const String& other) {
    this->str = other.str;
  }

  String operator+(const String& other) {
    return String(this->str + other.str);
  }

  void operator=(const String& other) {
    this->str = other.str;
  }

  void print() {
    cout << str << endl;
  }
};

int main() {
  String s1("Hello");
  String s2(" World!");
  String s3 = s1 + s2;
  s1.print();
  s2.print();
  s3.print();
  return 0;
}

相关问题