首页 > 解决方案 > cpp having a property with the same type of the same class

问题描述

Hello i wanted to have a chained object structure where in the class i have 2 properties of same the class type as the class inside of the class i working on. Like:

class Base;


class Base
{
    private:
       Base * m_prev;
       Base * m_next;

    public:
      Base (Base prev, Base next) {
        m_prev = prev;
        m_next = next;
      }
      void set_prev(Base *prev) ....
      void set_next(Base *next) ....
...
}

De compiler tells me that i use an unfinished type when i try the above, somehow i get that but there should be an way around it.

I have been a programmer on different languages like (delpi/pascal/java/javascript etc) and every one is different, now i'm trying to learn C++ now and i find it difficult to find the right documentation that can help me out.

I'm very sure there is a common solution for this but i could not find the right question to google.

Please can someone give a solution to this,

EDIT: While creating this post i forgot to add 2 setter lines (now added to this request) and made a follow-up question while i was in a hurry.

标签: c++classoopproperties

解决方案


Your constructor should be

Base (Base *prev, Base *next): m_prev(prev), m_next(next) {}

m_prev and m_next are pointers. You don't need the forward declaration. That's a working example:

class Base {
    private:
       Base *m_prev;
       Base *m_next;

    public:
      Base (Base *prev, Base *next): m_prev(prev), m_next(next) {}      
      void set_prev(Base *prev) { m_prev = prev; }
      void set_next(Base *next) { m_next = next; }

};

int main() {
    Base a(nullptr, nullptr); // a
    Base b(&a, nullptr); // a <- b
    a.set_next(&b); // a <-> b
    Base c(&a, &b); // a <-> b, a <- c -> b
    a.set_next(&c); // a <- b, a <-> c -> b
    b.set_prev(&c); // a <-> c <-> b
}

Of course, it's also possible to add some logic to avoid the manual relinking:

class Base {
    private:
       Base *m_prev;
       Base *m_next;

    public:
      Base (Base *prev, Base *next) {
          set_prev(prev);
          set_next(next);
      }      
      void set_prev(Base *prev) {
          m_prev = prev;
          if (m_prev) {
              m_prev->m_next = this;
          }
      }
      void set_next(Base *next) {
          m_next = next;
          if (m_next) {
              m_next->m_prev = this;
          }
      }

};

int main() {
    Base a(nullptr, nullptr); // a
    Base b(&a, nullptr); // a <-> b
    Base c(&a, &b); // a <-> c <-> b
}

There are still cases to handle in the second code like

    Base a(nullptr, nullptr); // a
    Base b(&a, nullptr); // a <-> b
    Base c(&a, &b); // a <-> c <-> b
    Base d(&a, &b); // a <-> d <-> b, a <- c -> b

推荐阅读