震撼:invalid use of undefined type

time_is_life 2007-09-14 01:48:30
有下面的代码:
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类,到底该怎么办那?

请高手指教,谢谢
...全文
1153 3 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
星羽 2007-09-14
  • 打赏
  • 举报
回复
把check放到外面去
nkgd 2007-09-14
  • 打赏
  • 举报
回复
放在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();
}
}
};
taodm 2007-09-14
  • 打赏
  • 举报
回复
那就check不要内联实现

65,184

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧