【问题标题】:Overloading operator+ for const char*为 const char* 重载 operator+
【发布时间】:2017-03-18 18:04:21
【问题描述】:
PString& PString::operator+(const PString &p) {
PString ps3;
ps3.rec = this->rec + p.rec;
return ps3;
}

这是我的函数的样子,这是我的 main()

PString ps1("Ovo je neki text");
PString ps2("ovo je neki drugi text");
PString ps3(ps1);
ps1 = ps2;
PString ps4;
ps4 = ps1 + ps2;
cout << ps4 << endl;

这是我收到的错误消息

vezba.cpp:99:29: error: invalid operands of types ‘char*’ and ‘char* const’ to binary ‘operator+’
 ps3.rec = this->rec + p.rec;
                         ^
vezba.cpp:98:13: warning: reference to local variable ‘ps3’ returned [-Wreturn-local-addr]
 PString ps3;

这是在我的课上:

class PString {
private:
char *rec;

好的,所以我把 operator+ 改成了这个

PString& PString::operator+(const PString &p) {
PString ps4;
std::string(ps4.rec) = std::string(this->rec) + std::string(p.rec);
return ps4;
}

现在我收到警告

vezba.cpp: In member function ‘PString& PString::operator+(const PString&)’:
vezba.cpp:98:13: warning: reference to local variable ‘ps4’ returned [-Wreturn-local-addr]
 PString ps4;

什么也没有打印出来

【问题讨论】:

  • 我是新来的,您能建议我如何改进吗?
  • PString 是 char* 的 typedef 吗?
  • 只是想知道,定义自己的字符串实现有什么意义,为什么不直接使用std::string??
  • 简短回答:char* 不是字符串。了解其中的区别。

标签: c++ overloading


【解决方案1】:

谷歌它:“operator+ const char”...example

引用 dlf:

operator+ 的右轴和左轴都是char*s。没有operator+ 的定义需要两个char*s(实际上,语言不允许你写一个)。

编辑:您可能应该使用std::string...

edit2:确定吗?微不足道的......

#include <iostream>
#include <string>

int main()
{
    std::string ps1("Ovo je neki text");
    std::string ps2("ovo je neki drugi text");
    std::string ps3(ps1);
    ps1 = ps2;
    std::string ps4;
    ps4 = ps1 + ps2;
    std::cout << ps4 << std::endl;
    return 0;
}

On codepad

【讨论】:

  • 我添加了一个例子......但它微不足道
【解决方案2】:

使用+ 进行字符串连接的最简单方法是使用标准库std::string。如果你想自己实现,你需要为你的 PString 类重载+。内置 char*s 不允许您将它们与 + 连接。

【讨论】:

  • 是的。在我发布之前我没有看到你的答案。
  • 天哪,你的代码很有趣。您通过在内部使用字符串来重新创建字符串类!为什么不删除 PString?
猜你喜欢
  • 1970-01-01
  • 2015-12-16
  • 2013-11-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多