我制作了以下程序,它有一个类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();
}
Run Code Online (Sandbox Code Playgroud)
所以,当我运行它.我没有在屏幕上显示任何内容,但是当我在cout之前删除"//"后运行程序时,程序正确显示正确的长度值.有人能为我提供这种行为的好解释吗?
在里面display你没有初始化i所以你打印随机垃圾,这恰好是0你的测试中的一个.打印出来length会在堆栈上放置一个0然后恰好初始化i.您的编译器应警告您有关读取未初始化的变量的信息.