C++에서 사용자 정의 C 유형 문자열 클래스를 작성해야한다는 지정이 있습니다. 이 문제를 해결하는 데 어려움을 겪고 있습니다. 현재 내 코드가 시작시 런타임 오류와 충돌합니다. 또한 많은 함수가 잘못되었음을 알고 있지만 다른 함수를 수정하기 전에 멤버 함수를 정렬해야합니다. 모든 함수 프로토 타입은 우리에게 주어 졌으므로 변경할 수는 없다는 것을 명심하십시오. 나는 말하기 위해 '배짱'을 쓸 필요가있다.C++에서 사용자 정의 C 유형 문자열 클래스 작성
처음에는 내 생성자가 잘못 되었나요?
#include <iostream>
#include "tstr.h"
using namespace std;
//Default constructor to initialize the string to null
TStr::TStr() {
strPtr = 0;
strSize = 0;
}
//constructor; conversion from the char string
TStr::TStr(const char *str) {
int i=0;
while (str[i] != '/0') {
strPtr = new char [strlen(str)+1];
for (i=0; i <strSize;++i) {
strPtr[i] = str[i];
}
++i;
}
strSize = i;
}
//Copy constructor
TStr::TStr(const TStr&) {
}
//Destructor
TStr::~TStr() {
if (strPtr) {
delete[] strPtr;
}
}
//subscript operators-checks for range
char& TStr::operator [] (int i) {
assert (i >= 0 && i < strSize);
return strPtr[i];
}
const char& TStr::operator [] (int i) const {
assert (i >= 0 && i < strSize);
return strPtr[i];
}
//overload the concatenation oprerator
TStr TStr::operator += (const TStr& str) {
//this->strPtr += str.strPtr;
//this->strSize += str.strSize;
return *this;
}
//overload the assignment operator
const TStr& TStr::operator = (const TStr& str) {
if (this != &str) {
delete[] strPtr;
strPtr = new char[strSize = str.strSize];
assert(strPtr);
for (int i=0; i<strSize; ++i) {
strPtr[i] = str.strPtr[i];
}
}
return *this;
}
//overload two relational operators as member functions
bool TStr::operator == (const TStr& str) const {
return (strPtr == str.strPtr && strSize == str.strSize);
}
bool TStr::operator < (const TStr& str) const {
return (strPtr < str.strPtr && strSize < str.strSize);
}
//the length of the string
int TStr::size() {
return strSize;
}
답장/도움 주셔서 감사합니다! :)
편집 1 : 알았습니다. 이제 생성자가 작동하지만 여전히 런타임 오류가 발생하고 90 %가 오버로드 된 + 연산자와 관련이 있다는 것을 확신합니다. 괜찮아 보이지만 괜찮아. 내가 뭘 놓치고 있니?
(참고 :. 만 작은 변화는 위의 코드 변경되었습니다,하지만 당신은 훨씬을보고 싶다면 알려주세요)
//overload the concatenation oprerator
TStr TStr::operator += (const TStr& str) {
for(int i = 0; i < strSize; ++i) {
strPtr[i] += str.strPtr[i];
}
return *this;
}
편집 2 : 좋아 내가 지금 가지고있는이. 컴파일은 잘되지만 두 문자열을 + =와 함께 실제로 추가하지는 않습니다. 누구든지 아이디어가있어?
//overload the concatenation oprerator
TStr TStr::operator += (const TStr& str) {
char *buffer = new char[strSize + str.strSize + 1];
strcpy(buffer, strPtr);
strcat(buffer, str.strPtr);
delete [] strPtr;
strPtr = buffer;
return *this;
}
//overload the assignment operator
const TStr& TStr::operator = (const TStr& str) {
if (this != &str) {
delete[] strPtr;
strPtr = new char[strSize = str.strSize];
assert(strPtr);
for (int i=0; i<strSize; ++i) {
strPtr[i] = str.strPtr[i];
}
}
return *this;
}
오타 (typo)인지 모르겠지만 NULL 종결자가 이스케이프 문자 대신 슬래시를 사용하고있는 것 같습니다. – Dawson
소멸자에서'if (strPtr)'를 확인할 필요가 없습니다. 'delete []'NULL 포인터는 nop이며 충돌하지 않습니다. –
또한 릴리즈 빌드에서 remove이기 때문에 아마'assert'를 사용해서는 안됩니다. 예외 사용. –