c++ - 通过运算符重载的字符串连接
问题描述
问题
编写一个 C++ 程序来重载“+”运算符来连接两个字符串。
该程序是在我的 Robert Lafore 第四版面向对象编程的 OOP 书中完成的,但似乎无法将 char 转换为字符串。该程序编写得很好并且满足了要求,但是它给出的一个错误使它难以理解。我似乎无法在其中找到问题。
它给出的错误是字符无法转换为字符串。
#include <iostream>
using namespace std;#include <string.h>
#include <stdlib.h>
class String //user-defined string type
{
private:
enum {
SZ = 80
}; //size of String objects
char str[SZ]; //holds a string
public:
String() //constructor, no args
{
strcpy(str, "");
}
String(char s[]) //constructor, one arg
{
strcpy(str, s);
}
void display() const //display the String
{
cout << str;
}
String operator + (String ss) const //add Strings
{
String temp;
if (strlen(str) + strlen(ss.str) < SZ) {
strcpy(temp.str, str); //copy this string to temp
strcat(temp.str, ss.str); //add the argument string
} else {
cout << “\nString overflow”;
exit(1);
}
return temp; //return temp String
}
};
////////////////////////////////MAIN////////////////////////////////
int main() {
String s1 = “\nMerry Christmas!“; //uses constructor 2
String s2 = “Happy new year!”; //uses constructor 2
String s3; //uses constructor 1
s1.display(); //display strings
s2.display();
s3.display();
s3 = s1 + s2; //add s2 to s1,
//assign to s3
s3.display();
cout << endl;
return 0;
}
解决方案
推荐阅读
- sql - id 3 的 SQL 查询返回匹配,其中 = 3XW3Z1zD6JEV1600164577
- java - 我的程序显示从 1 到 [用户输入],只是忽略了起始数字输入。有问题的代码是合数一
- c++ - 具有静态字段的对象和全局对象之间是否存在任何低级差异
- mysql - 使用 Node js 模型 MVC 创建 Web 服务器
- api - 使用 api 限制每天在 PowerBi 中添加新数据
- java - 每当有新客户端加入时,Java 服务器都会放弃旧客户端
- apache-kafka - Kafka配置:参数“cleanup.policy”和参数“log.cleanup.policy”有什么区别?
- mulesoft - MuleSoft 4 中的嵌套变量问题
- parquet - 无法使用 Redshift Spectrum 查询镶木地板数据
- python - 按未命名值而不是索引对 Pandas 系列进行排序