晚上好。抱歉标题我不能更准确地说明这个问题。
以下代码不显示任何内容,除非:
1. 我把开头的三个未使用的注释行删掉了,它们没有任何冲突。
2. 除非我在 main() 中将“Hello”更改为“Hello world”。
我正在使用代码块 10.05。
完整代码:
#include <iostream>
using namespace std;
class stringclass
{
protected :
inline bool success() { failbit = false; return true; } //line to ignore
inline bool fail() { failbit = true; return false; } //line to ignore
public :
bool failbit; //line to ignore
char * mystring;
long memsize;
long length;
void reset();
void alloc(long newsize);
void copy(const stringclass & other);
stringclass(const char str[]);
stringclass() {reset(); }
stringclass(const stringclass & other) {copy(other); }
~stringclass() {delete [] mystring;}
friend ostream& operator << (ostream& out, stringclass & obj) {out << obj.mystring; return out;}
};
void stringclass::reset()
{
delete [] mystring;
mystring = NULL;
length = 0;
memsize = 0;
}
void stringclass::alloc(long newsize)
{
delete [] mystring;
mystring = new char[newsize];
memsize = newsize;
mystring[0] = 0;
length = 0;
}
void stringclass::copy(const stringclass & other)
{
if(other.mystring == NULL) reset();
else
{
alloc(other.memsize);
strcpy(mystring, other.mystring);
length = strlen(mystring);
}
}
stringclass::stringclass(const char str[])
: mystring(NULL), memsize(0), length(0)
{
if(str == NULL) reset();
else
{
alloc(strlen(str) + 1);
strcpy(mystring, str);
length = strlen(mystring);
}
}
int main()
{
stringclass str = "Hello";
stringclass str2 = str;
cout << "str = " << str << endl;
cout << "str2 = " << str2 << endl;
cout << endl;
system("PAUSE");
return 0;
}
代码显示:
str =
str2 =
Press any key to continue...
代码更改后 1. :
str = Hello
str2 = Hello
Press any key to continue...
代码更改后 2. :
str = Hello world
str2 = Hello world
Press any key to continue...