【问题标题】:concatenating objects (C++) [duplicate]连接对象(C++)[重复]
【发布时间】:2020-06-30 23:19:46
【问题描述】:

他,我需要一些帮助,因为我无法弄清楚它在输出中显示什么奇怪的数字 我是说。例如 name_1 + name_2 有效,但我得到了额外的一些字符 Anna+Mark&@#$@@ 只是举例。

class String
{
private:
    char* str;
    int len;
    static int num_strings;
    static const int CINLIM = 80;
};

String& operator+(String& st, String& st2)
{
    char* napis = new char[st.len + st2.len]; 

    int i;
    for (i=0; st.str[i] != '\0'; i++)
    {
        napis[i] = st.str[i];
    }
    napis[i] = '+';

    int static j = i+1;
    for (int a = 0; st2.str[a] != '\0'; a++,j++)
    {
        napis[j] = st2.str[a];
    }
    st2.str[j] = '\0';
    for (int i = 0; i < j; i++)
    {
        cout << napis[i] << std::endl;
    }
    delete st.str;
    strcpy(st.str, napis);
    return st;
}

【问题讨论】:

  • 为什么j 是静态的?
  • 您没有为'\0''+' 分配空间。 char* napis = new char[st.len + st2.len + 2];
  • 另外,您 delete st.str 然后尝试将字符串复制到其中。在复制到新字符串之前,您需要为新字符串重新分配空间:st.str = new char[strlen(napis) + 1];
  • delete 应该是 delete[] 这里。在deleteing 之后,您正在使用st.str 立即。你可能打算在那里写st.str = napis
  • @JohnnyMopp 他们已经分配了一个新数组,它是napisst.str = napis 就是他们的意思。

标签: c++ string char operators


【解决方案1】:

您的代码中有多个 orpblems,但主要的是:

int static j = i+1;

静态函数变量只初始化一次(第一次)。我猜这不是你真正想要的,这一定是额外字符的原因(你只是使用之前调用函数的j的值,并且这个值总是增长)。您不需要变量是静态的。

还有一些问题: 为什么不使用 std::string? 即使你正在学习 C 风格的字符串管理,你也肯定需要在 ctors 中管理分配/释放。 考虑 cmets 中针对您的问题报告的其他问题。

【讨论】:

    猜你喜欢
    • 2016-08-25
    • 2015-07-05
    • 2021-04-22
    • 2021-06-11
    • 2012-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-30
    相关资源
    最近更新 更多