我的编译器使用指向不完整类型的"字符串"类的指针给出错误 E0393:Srep"在内联函数中是不允许的



我试图从一本书中编写自定义类型,我的编译器给出了一个错误E0393使用指针指向"字符串"的不完整类型;class:: Srep">

内联函数

我理解这个错误,但是如何修复它

class String {
struct Srep;
Srep* rep;
class Cref;
public:
class Range {};
String();
.....
~String();
inline void check(int i) const  {if (0 > i or rep->sz <= i) throw Range();}
inline char read(int i)const { return rep->s[i]; }
inline void write(char c, int i) { rep = rep->get_own_copy(); }
inline Cref operator[](int i) { check(i); return Cref(*this,i); }
inline char operator[](int i)const { check(i); return rep->s[i]; }
inline int size() const { return rep->sz; }
};
struct String::Srep
{
char* s;
int sz;
int n;
Srep(int nsz, const char* p)
{
n = 1;
sz = nsz;
s = new char[sz + 1];
strcpy(s, p);
}
~Srep() { delete[] s; }
Srep* get_own_copy()
{
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:           //предотвращаем копирование
Srep(const Srep&);
Srep operator= (const Srep);
};

就像您不需要在class中定义内联的嵌套类一样,您也不需要在class中定义内联函数。所以你要确保不管什么东西在使用之前都是定义好的。像这样:

#include <iostream>
class String {
struct Srep;
Srep* rep;
public:
class Range {};
inline void check(int i) const;
};
struct String::Srep {
int sz;
};
void String::check(int i) const {
if (0 > i or rep->sz <= i) throw Range();
}
int main() {
std::cout << "works!n";
}

最新更新