C ++ #include循环 [英] C++ #include Loop

查看:168
本文介绍了C ++ #include循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

File Dog.h

#ifndef DOG_H
#define DOG_H

#include "Cat.h"
//class Cat;

class Dog
{
        Cat c;
};

#endif

文件Cat.h

#ifndef CAT_H
#define CAT_H

#include "Dog.h"
//class Dog;

class Cat
{
        Dog d;
};

#endif

这会导致循环,问题在于两个类需要了解彼此;前向声明也没有解决问题。您可以创建Dog d或Cat c的指针来解决它。

This causes a loop, the problem is that both classes needs to know about each other; forward declaration doesn't solve the problem either. You can create a pointer of either Dog d or Cat c to solve it.

问题:是否真的没有办法不创建指针,即保持代码不变,而不重写我想要的代码?

Question: Is there really no way of not creating a pointer, i.e keep the code as it is without rewrite of how I want it to be?

推荐答案

你要做的事情是不可能的。你的课将占用无限空间。

What you're trying to do is impossible. Your class would take infinite space.

你有一个,它有一个 Cat 成员变量,它有一个 Dog 成员变量,它有一个 Cat 成员变量,有一个成员变量......

You got a Dog which has a Cat member variable, which has a Dog member variable, which has a Cat member variable, which has a Dog member variable...

如果没有用指针打破某个地方,你最终会无限带有无限内存的递归成员变量是不可能的。

Without breaking it somewhere with a pointer you'll end up with infinite recursive member variables taking infinite memory which is not possible.

注意,编译器甚至无法实际计算 Dog Cat 。但是由于C ++中的类通常不能 0 大小,我们知道无论如何它都是无限空间。

Note that the compiler can't even actually calculate the memory needed for Dog or Cat due to the infinite recursion. But since a class in C++ can't be 0 size normally, we know that it'll be infinite space anyways.

其他答案也提供了很好的观点,即鸡和蛋问题,必须首先定义哪一个才能定义另一个。

The other answers give nice perspectives too, i.e. 'Chicken and Egg' problem of which one has to be defined first to be able to define the other.

我只是想补充说,相互递归的类是奇怪的,如果你可以用其他方式设计它,最好避免。如果你真的必须使用它们,请确保你实际上打破了递归。否则你只是从编译时的错误转移它,因为无限的相互递归到内存不足和运行时崩溃,如果你有一个天真的实现,指针执行无限的相互递归 new 在施工时调用。

I just wanna add that mutually recursive classes are something strange and best avoided if you can design it some other way. If you really have to use them make sure that you actually break the recursiveness. Otherwise you shift it only from an error at compile time due to infinite mutual recursion to running out of memory and an crash at runtime if you got a naive implementation with pointers that does infinite mutually recursive new calls at construction time.

这篇关于C ++ #include循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆