读书人

震撼:invalid use of undefined type

发布时间: 2012-02-15 12:09:44 作者: rapoo

震撼:invalid use of undefined type
有下面的代码:
using namespace std;
class String
{
struct Srep; //representation.
Srep* rep;

public:
class CRef; //reference to char
class Range{}; //for exceptions

String(); // x= " "
String( const char* ); //x= "abc "
String( const String& ); //x=other_string
String& operator=(const char* );
String& operator=(const String&);
~String();

void check( int i ) const
{
if( i < 0 || rep-> sz <= i ) // <-这一句编译报错: invalid use of undefined type `struct String::Srep '
{
throw Range();
}
}
};

struct String::Srep
{
char* s; //pointer to elements
int sz; //number of characters
int n; //reference count;

Srep( int nsz, const char* p )
{
n = 1;
sz = nsz;
s = new char[sz+1]; //add space for teminitor
strcpy(s,p);
}

~Srep() { delete[] s; }

Srep* get_own_copy() //clone if necessary
{
if( n== 1 ) return this;
n--;
return new Srep( sz , s );
}

void assign( int nsz , const char* p )
{
if( sz != nsz )
{
delete[] s;
sz = nsz;
s = new char[sz+1];
}
strcpy( s, p );
}

private: //prevent copying


Srep( const Srep& );
Srep operator=(const Srep&);
};

编译出错的部分在这里
void check( int i ) const
{
if( i < 0 || rep-> sz <= i ) // <-这一句编译报错: invalid use of undefined type `struct String::Srep '
{
throw Range();
}
}
根据错误提示,因为我把struct String::Srep的定义放在了下面,所以这里找不到struct String::Srep的定义,
可是如果我把struct String::Srep的定义放在String类定义的上面,又会提示找不到String类,到底该怎么办那?

请高手指教,谢谢

[解决办法]
那就check不要内联实现
[解决办法]
放在String类的里面
class String
{
struct Srep
{
char* s; //pointer to elements
int sz; //number of characters
int n; //reference count;

Srep( int nsz, const char* p )
{
n = 1;
sz = nsz;
s = new char[sz+1]; //add space for teminitor
strcpy(s,p);
}

~Srep() { delete[] s; }

Srep* get_own_copy() //clone if necessary
{
if( n== 1 ) return this;
n--;
return new Srep( sz , s );
}

void assign( int nsz , const char* p )
{
if( sz != nsz )
{
delete[] s;
sz = nsz;
s = new char[sz+1];
}
strcpy( s, p );
}

private: //prevent copying
Srep( const Srep& );
Srep operator=(const Srep&);
};

Srep* rep;

public:
class CRef; //reference to char
class Range{}; //for exceptions

String(); // x= " "
String( const char* ); //x= "abc "
String( const String& ); //x=other_string
String& operator=(const char* );
String& operator=(const String&);
~String();

void check( int i ) const
{
if( i < 0 || rep-> sz <= i )
{
throw Range();
}
}
};
[解决办法]
把check放到外面去

读书人网 >C++

热点推荐