我正在尝试创建自己的字符串类,该类执行一些基本的字符串操作。但是,我的代码无法正常工作。它可以运行,但不输出任何内容,而且我似乎找不到错误。任何帮助将不胜感激。下面的代码:
.h文件-
#ifndef PART_2_H_INCLUDED #define PART_2_H_INCLUDED class String { public: int str_size; char *str; String() { str = nullptr; str_size = 0; } String(const char *usrstr); String(String &usrstr); String& operator = (const String& usrstr); String operator + (const String& usrstr1); char *c_str(); int length(); void clear(); ~String() { delete [] str; } }; #endif // PART_2_H_INCLUDED
.cpp文件-
#include <iostream>
#include "Part_2.h"
#include <cstring>
using namespace std;
int String::length()
{
int i = 0;
while(str[i] != '\0')
i++;
return i;
}
String::String(const char *usrstr)
{
int i = 0;
while(usrstr[i] != str_size)
{
i++;
}
int usrstrlen = i;
this->str_size = usrstrlen;
str = new char[str_size];
i = 0;
while(i < this->str_size)
{
this->str[i] = usrstr[i];
i++;
}
}
String::String(String &usrstr)
{
int i = 0;
this->str_size = usrstr.str_size;
str = new char[this->str_size];
while(i < this->str_size)
{
this->str[i] = usrstr.str[i];
i++;
}
}
String& String::operator = (const String& usrstr)
{
int i = 0;
this->str_size = usrstr.str_size;
this->str = new char[this->str_size];
while(i < this->str_size)
{
this->str[i] = usrstr.str[i];
i++;
}
return *this;
}
String String::operator + (const String& usrstr1)
{
String obj;
int i = 0;
int j = 0;
obj.str_size = this->str_size + usrstr1.str_size;
obj.str = new char[obj.str_size];
while(i < this->str_size)
{
obj.str[i] = this->str[i];
i++;
}
while(j < usrstr1.str_size)
{
obj.str[i] = usrstr1.str[j];
i++;
j++;
}
cout << obj.str;
return obj;
}
char* String::c_str()
{
char *cstring = new char[this->str_size + 1];
int i = 0;
while(i < this->str_size)
{
cstring[i] = this->str[i];
i++;
}
cstring[i] = '\0';
return cstring;
}
void String::clear()
{
int i = 0;
while(i < this->str_size)
{
this->str[i] = '\0';
i++;
}
this->str_size = 0;
}
int main(){
String obj1("Testing");
String obj2(obj1);
String obj3=obj2;
cout << obj1.str << endl;
cout << obj3.str << endl;
obj3.clear();
cout << obj3.str;
cout << obj1.length();
return 0;
}
对于任何菜鸟错误我深表歉意。