0

クラスの操作を開始したばかりで、このコードでは、ユーザーから文字列を取得し、その長さをカウントしてから出力するクラスを作成しようとしています。しかし、何のためにあるのか理解できないエラーがいくつか発生しています。助けていただければ幸いです。

#include<iostream>

using namespace std;

class String
{
public:
    String();  // constructor
    void Print();   // printing the string
    void Get();     // getting the string from the user.
    int CountLng( char *);   // counting length
    ~String();  // destructor

private:
    char *str;
    int lng;
} str1;


String::String()
{
    lng=0;
    str=NULL;

}


int CountLng( char *str)
{
    char * temp;
    temp=str;
    int size=0;
    while( temp !=NULL)
    {
        size++;
        temp++;
    }

    return size;


};

void String::Get()

{
    str= new char [50];
    cout<<"Enter a string: "<<endl;
    cin>>str;


};


void String::Print()
{
    cout<<"Your string is : "<<str<<endl<<endl;
    lng= CountLng( str);
    cout<<"The length of your string is : "<<lng<<endl<<endl;
};



int main()
{



    str1.Get();
    str1.Print();

    system("pause");
    return 0;
}
4

3 に答える 3

1

このCountLng()メソッドでは、文字列の末尾を確認するには、ポインターの場所自体ではなく、ポインターが指す場所の内容を確認する必要があります。

while( *temp !='\0')//*temp gives you the value but temp gives you the memory location
{
    size++;
    temp++;
}

文字列の末尾をチェックする基準は、文字'\0'またはNUL. 文字列の末尾を指すポインターは、NULL である必要はありません。

さらに、このGet()メソッドでは、文字列のサイズが 50 文字に制限されています。これは、2 つの String オブジェクトを一緒に追加するときに問題になります。std::copy を使用して文字列サイズを動的にし、文字配列を再割り当てし、オーバーフローの場合に文字列サイズを大きくする必要があります。

于 2013-04-13T09:09:48.113 に答える
0
  1. int CountLng(char *str)int String::CountLng(char *str)それはStringクラスのメソッドだからです。

  2. また、クラス宣言でデストラクタを定義しましたが、彼の本体を定義していませんでした:

String::~String() { }

于 2013-04-13T09:03:21.250 に答える
-1

上記のコードには複数の問題があります

  1. 文字列オブジェクトであるはずの str1 を使用していますが、宣言していません。
  2. メンバー関数は :: 構文で宣言されています
  3. デストラクタには本体がありません

これらの問題を取り除くためにプログラムを微調整しました。元のプログラムと比較して違いを確認してください

#include<iostream>

using namespace std;

class String
{
public:
    String();  // constructor
    void Print();   // printing the string
    void Get();     // getting the string from the user.
    int CountLng( char *);   // counting length
    ~String(){ if (str) delete []str; };  // destructor

private:
    char *str;
    int lng;
};


String::String()
{
    lng=0;
    str=NULL;

}


int String::CountLng( char *str)
{
    char * temp;
    temp=str;
    int size=0;
    while( *temp !='\0')
    {
        size++;
        temp++;
    }

    return size;


};

void String::Get()

{
    str= new char [50];
    cout<<"Enter a string: "<<endl;
    cin>>str;


};


void String::Print()
{
    cout<<"Your string is : "<<str<<endl<<endl;
    lng= CountLng( str);
    cout<<"The length of your string is : "<<lng<<endl<<endl;
};



int main()
{

    String str1;

    str1.Get();
    str1.Print();

    system("pause");
    return 0;
}
于 2013-04-13T09:03:55.613 に答える