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 个字符。当将两个 String 对象相加时,这将是一个问题。您需要通过使用 std::copy 和重新分配您的 char 数组来使字符串大小动态化,并在溢出的情况下使您的字符串大小更大。

于 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 回答