【问题标题】:How do you create a class which can hold itself as a variable in c++? [duplicate]您如何创建一个可以将自己作为 C++ 中的变量保存的类? [复制]
【发布时间】:2019-02-09 09:20:06
【问题描述】:

我对 c++ 相当陌生,我的大部分写作都是用 Python 编写的。

在 Python 中,如果我想创建一个类来保存有关人类的信息,我可以编写一个可以将其“父级”作为其变量之一的类。在 Python 中,我大致会这样做:

class Human:

    def __init__(self, name):
        self.name = name


first = Human("first")
second = Human("second")

second.parent = first

second.parent = first 表示人类 second 的父级是人类 first

在 c++ 中我尝试实现类似的东西:

class Human {

    public:
        Human parent;

};

int main() {
    Human first = Human();
    Human second = Human();

    second.parent = first;
}

此示例带有field has incomplete type: Human 的错误。我明白了,因为它说我的 Human 对象中不能有 Human,因为还没有对 Human 是什么的完整定义。当我搜索相关帖子时,我不断提出使用前向声明和指针的解决方案,但我无法使其正常工作。

如果能帮助我使 c++ 示例按照我想要的方式运行,我将不胜感激。

谢谢。

【问题讨论】:

  • 你应该使用parent的引用或指针
  • 第一:你不能。第二:在您的用例中没有任何意义。因此,如 πάντα ῥεῖ 所说,请使用指针或引用。您不希望您的孩子拥有父类的完整副本!
  • 你想做的声明就像一个无限的matroschka。困难可能在于意识到在 C++ 中值是值而不是引用

标签: c++ class oop forward-declaration incomplete-type


【解决方案1】:

你能做的是

class Human {

public:
    Human * parent = nullptr;

};

它应该是一个指针,并且更好地初始化。

【讨论】:

  • 实际的问题是,要声明Human 的成员,编译器需要知道需要多少空间。但为此,它需要知道Human 中有多少空间,ad infinitum
【解决方案2】:

您可以通过在相同类型的类中保留一个指针属性来做到这一点。 喜欢

class Human {
...
...
public : Human* parent;
...
...
}

并且可以用作:

int main()
{
    Human* h1 = new Human;
    Human* h2 = new Human;

    h2->parent = h1;
    ...
    ...
    delete h1;
    delete h2;
}

【讨论】:

  • 这段代码引入了内存泄漏(h1h2 没有delete)。无论如何,使用智能指针代替new 是一种更好的做法。
  • 已按建议更新,感谢指点。
【解决方案3】:

指针在这里有意义,指针将内存地址保存到您所引用的任何内容,而不会将实际数据存储在该类中。

E.G

class Human {

public:
    Human * parent;

};

您的父母现在实际上存储为内存地址,但使用 *parent 它正在使用一个对象,例如您可以这样做: myHuman.parent->parent(-> 表示取消引用,然后是“.”)

【讨论】:

    【解决方案4】:

    例如使用指针:

    struct Human
    {
        Human* parent;  // The symbol Human is declared, it's okay to use pointers to incomplete structures
    };
    
    int main()
    {
        Human first = Human();
        Human second = Human();
    
        second.parent = &first;  // The & operator is the address-of operator, &first returns a pointer to first
    }
    

    您也可以使用引用,但使用和初始化这些引用可能会有点困难。

    【讨论】:

    • 问题解决了!我认为我让指针和地址在我的大脑中被打乱了,但这帮助我解决了所有问题
    • 虽然指针(和引用)是正确且直观的选择,但值得一提的是其他选择,例如:std::unique_ptrstd::shared_ptrstd::weak_ptr,另见:stackoverflow.com/questions/63365537/c-instance-of-same-class/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-29
    • 2023-03-08
    • 1970-01-01
    • 2011-02-23
    • 2021-06-02
    • 1970-01-01
    • 2014-09-13
    相关资源
    最近更新 更多