gpt4 book ai didi

c++ - 创建没有字符串库的字符串类

转载 作者:行者123 更新时间:2023-11-30 04:17:09 25 4
gpt4 key购买 nike

我试图在不使用字符串库的情况下创建自己的字符串类。 #include <string>

我可以使用 C 风格的字符串!

我必须制作 iString ctor、复制 ctor、dtor 并重载运算符 >>、<<、+、*

到目前为止,我的问题是,当我尝试编译我的作品时,我的每个 operator+ 都出现了这个错误。和 operator* ...这是:

warning: reference to local variable s3 returned [enabled by default]

s3只是iString对象名称。

这是我目前所拥有的:

.h文件

#ifndef __ISTRING_H__
#define __ISTRING_H__

struct iString{
char * chars;
unsigned int length;
unsigned int capacity;
iString(); // ctor
iString(const char *); // copy ctor
iString(const iString&); // copy ctor
~iString(); // dtor
};

std::istream &operator>>(std::istream &in, const iString &s);
std::ostream &operator<<(std::ostream &out, const iString &s);
iString &operator+(const iString &s1, const iString &s2);
iString &operator+(const iString &s1, const char *c_str);
iString &operator*(const iString &s, const int k);
iString &operator*(const int k, const iString &s);


#endif

.cc 文件

#include <iostream>
#include "istring.h"
#include <cstring>

using namespace std;

iString::iString(){ // this is my ctor
chars = new char[1];
length = 0;
capacity = length + 1;
chars[0] = '\0';
}

iString::iString(const char *word){ // this is my copy ctor from a c-string
length = strlen(word);
capacity = length + 1;
chars = new char[capacity];
strcpy(chars, word);
}

iString::iString(const iString &s){ // this is my copy ctor from an iString
length = strlen(s.length);
capacity = length + 1;
chars = new char[capacity];
strcpy(chars, s.chars);
}


iString::~iString() { //dtor
delete [] this->chars;
}

istream &operator>>(istream &in, const iString &s){ // not done, don't worry

}

ostream &operator<<(ostream &out, const iString &s){
//out<<s.chars;
return out<<s.chars;
}

iString &operator+(const iString &s1, const iString &s2){
iString s3;

char *new_str;// = new char[size];
new_str = strcat(s1.chars, s2.chars);

s3 = iString(new_str);
return s3;
}

// tried a different approach
iString &operator+(const iString &s1, const char *c_str){

int size = s1.length + strlen(c_str) + 1;
char *new_str = new char[size];

strcpy(new_str, s1.chars);
strcat(new_str, c_str);

iString s3(new_str);
delete [] new_str;
return s3;
}

iString &operator*(const iString &s, const int k){

int size = (s.length * k) + 1;
char *c_str = new char[size];
for(int i = 0; i < k; i++){
strcat(c_str, s.chars);
}

iString t(c_str);
delete[] c_str;
return t;
}

iString &operator*(const int k, const iString &s){
return s * k;
}

最佳答案

您不应该从 operator+( , ) 返回引用

iString operator+(const iString &s1, const iString &s2){
...
}

关于c++ - 创建没有字符串库的字符串类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17267337/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com