これをデバッグで実行しました。String Substring 関数では、return ステートメントまですべてが機能します。
以下のコードの「returnString」は、戻り行にあるときに正しい値を持ちます。ただし、次の行 (直後の閉じ括弧) に移動するとすぐに、次のように変わります。
{Text=0x003ed0e0 "îþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþ... }String
デストラクタまでさかのぼると、削除されたときに文字列が持つ値です。
さて、値が渡された後にのみ値が削除されると思っていたでしょうが、最初に削除されているようです。これを修正する方法を知っていますか?上で述べたように、関数は完全に機能します (少なくとも、そのように見えます)。値を返す方法に問題があります。
私の文字列関数を呼び出す行:(String LocalString((Address.Substring(0, atIndex)));
アドレスは、それぞれのヘッダーファイルの「プライベート」の下で文字列として宣言されています)
部分文字列は、インデックス演算子の直後、中途半端です。関数またはファイルが不足しているように思われる場合は、それを求めてください。読んでくれてありがとう(私は望んでいる)助けを。
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;
*/