gpt4 book ai didi

c++ - 无法使用用户定义的字符串类显示字符串

转载 作者:太空宇宙 更新时间:2023-11-04 16:12:03 24 4
gpt4 key购买 nike

我制作了以下程序,它有一个 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();

}

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

最佳答案

display 中你没有初始化 i 所以你打印随机垃圾,它在你的测试中恰好是一个 0。打印出 length 恰好将 0 放入堆栈,然后恰好初始化 i。您的编译器应该警告您读取未初始化的变量。

关于c++ - 无法使用用户定义的字符串类显示字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27582731/

24 4 0
文章推荐: html - 在 HTML 表格中设置列宽
文章推荐: html - IE9 Bug div 在悬停 anchor 标记时跳转
文章推荐: jquery - 如何避免
文章推荐: c++ - 重载调用不明确
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com