我做了下面的程序,它有一个类字符串,这将作为用户定义的字符串类型。无法显示字符串使用用户定义字符串类
#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之前删除“//”后运行程序时,程序正确显示正确的长度值。任何人都可以为我提供一个很好的解释这种行为?
[无法重现问题](http://ideone.com/5XeLGY) –
这适用于我。 http://ideone.com/HM3clk – shuttle87
虽然while循环会更好地表达为for循环,但是无论如何,您是否尝试过使用调试器来逐步完成它?循环条件可能永远不会被满足。另外,尝试在显示调用后添加'std :: cout << std :: flush'。 – OMGtechy