2014-12-20 23 views
0

我做了下面的程序,它有一个类字符串,这将作为用户定义的字符串类型。无法显示字符串使用用户定义字符串类

#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之前删除“//”后运行程序时,程序正确显示正确的长度值。任何人都可以为我提供一个很好的解释这种行为?

+3

[无法重现问题](http://ideone.com/5XeLGY) –

+2

这适用于我。 http://ideone.com/HM3clk – shuttle87

+0

虽然while循环会更好地表达为for循环,但是无论如何,您是否尝试过使用调试器来逐步完成它?循环条件可能永远不会被满足。另外,尝试在显示调用后添加'std :: cout << std :: flush'。 – OMGtechy

回答

5

里面display你不初始化i所以你打印随机垃圾,这恰好是在你的测试0。打印出length恰好将0放在堆栈上,然后恰好初始化为i。你的编译器应该警告你阅读一个未初始化的变量。

+1

不错的发现!这里最大的错误是禁用或忽略了可以回答这个问题的编译器警告。 –

+1

我只有这个警告:43 C:\ Users \ dell \ Documents \ Untitled2.cpp \t [警告]不推荐将字符串常量转换为'char *'[-Wwrite-strings]但是初始化i = 0 ..谢谢! – Smatik

+0

@Smatik,这意味着你有重要的警告被禁用。 –

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' 
    }