【问题标题】:I new to programming and study about operator overloading. To overload "+" to add two string我是编程新手,学习运算符重载。重载“+”以添加两个字符串
【发布时间】:2017-04-08 13:11:32
【问题描述】:

我刚接触编程和学习运算符重载。重载“+”以添加两个字符串。但是当我尝试使用 strcpy 组合两个字符串时,第二个字符串会替换第一个字符串而不是用第一个字符串复制。

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

using namespace std;

class String
{
    char str[100];
public:
    void operator +(String);
     String()
     {
         strcpy(str,"");
     }
     String(char a[100])
     {
         strcpy(str,a);

     }

};

void String::operator+ (String str1)
{ char temp[100];
  strcpy(temp,str);
  strcpy(temp,str1.str);
  cout<<temp;
}
int main()
{
    String s1=String("Hello");;
    String s2=String("World");
    s1+s2;


    return 0;
}

【问题讨论】:

    标签: operator-overloading strcpy string.h


    【解决方案1】:

    您的代码中的错误是 在运算符重载函数中,您应该使用 strcat - 字符串连接 欲了解更多信息,请查看:String concatenation

    【讨论】:

      【解决方案2】:

      我认为您错过了将两个字符串的值分配给这样的新字符串:

      String nString = s1 + s2;
      

      【讨论】:

        猜你喜欢
        • 2010-12-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-06
        • 2020-12-13
        • 1970-01-01
        • 2017-02-05
        • 1970-01-01
        相关资源
        最近更新 更多