c++ - 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.
解决方案
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
推荐阅读
- python - Django:将外键限制为仅具有相同ID的行
- mysql - 库存系统/任务系统的正确计数
- node.js - 我可以将一组对象发送到控制器中的视图,与 node/express/mongoose 中的 mongodb 对象相关联吗?
- sql - Comparing between two dates in Oracle DB is not giving proper result
- javascript - Dynamic YouTube Video page - Get current Video ID & Title
- ios - Xamarin application does not work in ad-hoc mode
- authentication - Xamarin.Auth 或 IdentityModel + IdentityServer4
- python - Pandas:基于 pandas 列中匹配子字符串的 Groupby
- java - 在 Java 中声明常量的最佳方式
- javascript - 如何过滤有时值为空的数组?