无法使用用户定义String类显示字符串

时间:2014-12-20 17:44:41

标签: c++ constructor

我制作了以下程序,它有一个类String,可以作为用户定义的字符串类型。

#include<iostream>

using namespace std;

class String{
    char *s;

    public:
        int length;
        String()
        {
            s=NULL;
            length=0;

        }
        String(char *ss)
        {
            int count=0;
            while(*ss!='\0')
            {
                count ++;
                ss++;

            }
            ss=ss-count;
            s=new char[count];
            length = count;
            s=ss;
        }
        void display()
        {
            int i;
            while (*(s+i)!='\0')
            {
                cout<<*(s+i);
                i++;
            }
        }
};

int main()
{
    String s1("Hello World");
    //cout<<s1.length;                 //<------remove the // before cout and voila!
    s1.display();

}

所以,当我运行它。我没有在屏幕上显示任何内容但是当我在删除&#34; //&#34;之后运行程序时在cout之前,程序正确显示正确的长度值。任何人都能为我提供这种行为的好解释吗?

2 个答案:

答案 0 :(得分:5)

display内部,您不会初始化i,因此您可以打印随机垃圾,这在您的测试中恰好是0。打印出length恰好在堆栈上放置0,然后恰好初始化i。您的编译器应警告您有关读取未初始化的变量的信息。

答案 1 :(得分:0)

你的逻辑要复杂得多。

    String(char *ss)          <<< This is source string.
    {
        int count=0;
        while(*ss!='\0')
        {
            count ++;         <<< count will not account for '\0'.
            ss++;

        }
        ss=ss-count;
        s=new char[count];    <<< You are allocating space for 's'
        length = count;
        s=ss;                 <<< And then you are making 's' point to 'ss'
    }