gpt4 book ai didi

c++ - 使用 string.h 制作简单的 String 类

转载 作者:搜寻专家 更新时间:2023-10-31 01:37:29 25 4
gpt4 key购买 nike

我必须使用 string.h 构建一个 String 类(当您看到代码时您就会明白)。请原谅我糟糕的英语。我不知道问题出在哪里。它只是崩溃而没有任何错误消息。

(String.h)

#ifndef _STRING_H
#define _STRING_H

class String{
public:
char* s1;
char* s2;
char* stemp;


//The Constructors
String();
String(char* so);
String(char* so, char* st);

//Member Functions
int slength(char* s1); //Calculate the length of Sting
void scopy(char* so,const char* st); // copy string value to another String


};



#endif // _STRING_H

(String.cpp)

#include <string.h>
#include "String.h"

//The Constructors
String::String(){}

String::String(char* so){
s1 = so;
}
String::String(char* so, char* st){
s1 = so;
s2 = st;
}


//Member Functions

int String::slength(char* so){
return strlen(so);
}

void String::scopy(char* so,const char* st){

strcpy(so,st);
}

(main.cpp)

#include <iostream>
#include "String.h"


using namespace std;

int main()
{

String str("Hello","World");


cout<<"The First String is : "<<str.s1<<endl;
cout<<"The Second String is : "<<str.s2<<endl;
cout<<"-------------------------------------"<<endl;

cout<<"The First String contains "<<str.slength(str.s1)<<" Letters"<<endl;
cout<<"The Second String contains "<<str.slength(str.s2)<<" Letters"<<endl;

cout<<"-------------------------------------"<<endl;

cout<<"Copying The Second String in the First String . . ."<<endl;
str.scopy(str.s1,str.s2);
cout<<"The First String is : "<<str.s1<<endl;
cout<<"The Second String is : "<<str.s2<<endl;


return 0;
}

最佳答案

一个字符串文字被分配给 str.s1,并作为 strcpy 的第一个参数传递给 String::scopy() >。这非常糟糕,因为不允许修改字符串文字。

关于c++ - 使用 string.h 制作简单的 String 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34090278/

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