一个简单的类,用于获取和打印字符串

A simple class for getting and printing a string

本文关键字:用于 获取 字符串 打印 一个 简单      更新时间:2023-10-16

我刚刚开始使用类,在这段代码中,我试图有一个类,从用户获得一个字符串,计算它的长度,然后打印它。但是我得到了一些错误,我不明白它们是用来干什么的。我很感激你的帮助。

#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;
}

CountLng()方法中,要检查字符串的结束,您需要检查指针指向的位置的内容,而不是指针位置本身:

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

检查字符串结尾的标准是查找字符''NUL。指向字符串末尾的指针不一定是NULL。

此外,在Get()方法中,字符串大小被限制为50个字符。当将两个String对象一起添加时,这将是一个问题。您需要使用std::copy和重新分配您的字符数组,使字符串大小动态,并使您的字符串大小在溢出的情况下更大

  1. int CountLng(char *str)应该是int String::CountLng(char *str),因为它是String类的方法

  2. 同样,你在类声明中定义了析构函数,但没有定义析构函数体:

String::~String() { }

以上代码有多个问题

  1. 你正在使用str1 a应该是字符串对象,但没有声明它。
  2. 成员函数用::语法声明
  3. Destructor没有body

我已经调整了你的程序,以摆脱这些问题,比较它与你的原始程序,看看差异

#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 !='')
    {
        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;
}