我通过调试运行它,在String Substring函数中,一切都可以运行,直到return语句。
'returnString',在下面的代码中,在返回行时具有正确的值。但是,只要我转到下一行(后面的右括号),它就会变为:
{Text=0x003ed0e0 "îþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþ... }String
是String在删除时的值。
现在,我会认为该值只有在传递后才会被删除,但它似乎首先被删除了。你们知道如何解决这个问题吗?就像我上面说的那样,该函数完美地工作(至少看起来像它),它返回值的方式有点不对。
调用我的字符串函数的行:String LocalString((Address.Substring(0, atIndex)));
(Address在相应的头文件中声明为'private'下的字符串)
子串已经过了一半,就在索引运算符之后。如果看起来我错过了一个函数或文件,请求它。感谢阅读和(我希望)帮助。
String.h 文件:
#pragma once
#include <iostream>
#include <sstream>
using namespace std;
// C++ String class that encapsulates an ASCII C-string
class String
{
public:
// Default constructor
String()
{
Text = NULL;
}
// MUST HAVE: Copy-constructor that performs deep copy
String(const String& source)
{
Text = NULL;
// Call the assignment operator to perform deep copy
*this = source;
}
// Init-constructor to initialize this String with a C-string
String(const char* text)
{
Text = NULL;
// Call the assignment operator to perform deep copy
*this = text;
}
// Destructor
~String()
{
delete[] Text;
}
// Returns the count of characters in a C-string text; NULL-terminator is not counted
static int GetLength(const char* text)
{
int x = 0;
while(text[x] != '\0')
x++;
return x;
}
// Assignment operator to perform deep copy
String& operator = (const char* text)
{
// Ddispose of old Text
delete[] Text;
// +1 accounts for NULL-terminator
int trueLength = GetLength(text) + 1;
// Dynamically allocate characters on heap
Text = new char[trueLength];
// Copy all characters from source to Text; +1 accounts for NULL-terminator
for ( int i = 0; i < trueLength; i++ )
Text[i] = text[i];
return *this;
}
// if length is not specified, then the substring spans from startPosition until the end of this String
// throws an exception when startPosition is out of bounds
String Substring(int startPosition, int length=0) const
{
char * str = this->GetText();
int strLength = length;
int x = 0;
char* substring = new char[strLength];
while(x < strLength && str[x+startPosition]!='\0')
{
substring[x] = str[x + startPosition];
x++;
}
substring[x]='\0';
String returnString = substring;
return returnString;
}
// Returns the count of characters in the String; NULL-terminator is not counted
int GetLength() const
{
return GetLength(Text);
}
private:
// The encapsulated C-string
char* Text;
};
在main.cpp的某个地方...
String LocalString((Address.Substring(0, atIndex)));
String DomainString((Address.Substring(atIndex + 1)));
// or, in simpler syntax:
/*
* String hell0 = String andGoodbye;
* String smile = String andWave;
*/
答案 0 :(得分:4)
尽管注释// Assignment operator to perform deep copy
,但该类没有用户定义的赋值运算符。
默认的,计算机生成的赋值运算符执行浅表复制。一旦一个副本被销毁,所包含的文本就会丢失。