简体   繁体   中英

my compiler gives an error E0393 using a pointer to an incomplete type of the "String" class::Srep" is not allowed in inline functions

I tried to write a custom type from a book, my compiler gives an error E0393 using a pointer to an incomplete type of the "String" class::Srep" is not allowed

in inline functions

I understand this error, but how to fix it

 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);
};

Like you do not need to define nested classes inline in class you also do not need to define inline functions inline in class. And so you make sure that whatever some thing uses is defined before usage. Like that:

#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";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM