向前声明基类 [英] Forward Declaration of a Base Class

查看:102
本文介绍了向前声明基类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建不包含很多其他文件的正确头文件。

(要保持它们的清洁,以加快编译时间,...)



我在执行此操作时遇到两个问题:



1 - 基类上的转发声明无效。

  B类; 

A类:public B
{

// ...
}

2 - STD类的转发声明无效。

  namespace std 
{
class string;
}

class A
{
string aStringToTest;
}

如何解决这些问题?



第二个问题与标准无关库类。这是因为你将类的实例声明为你自己的类的成员。



这两个问题都是由于编译器必须能够找到总数



然而,编译器可以计算出指向类的指针的大小,即使它还没有完整的定义的。所以在这种情况下一个可能的解决方案是在消费类中有一个指针(或引用)成员。



在基类中没有太多帮助, 。



对于 std :: string 这样的东西也不值得。首先,它应该是一个方便的包装器,围绕字符缓冲区,以节省你对内存管理这么简单。



其次(如评论中所指出的那样)。如果你有一个指向它的指针, ), std :: string std :: basic_string< char> 的typedef。所以你需要转发declare(然后使用),而不是,事情变得非常晦涩难以阅读,这是另一种成本。是真的值得吗?


I'm trying to create proper header files that don't include much other files.
(To keep them clean, to speed up compiling time, ...)

I encountered two problems while doing this:

1 - Forward declaratoin on base classes doesn't work.

class B;

class A : public B
{

    // ...
}

2 - Forward declaration on STD classes doesn't work.

namespace std
{
    class string;
}

class A
{
    string aStringToTest;
}

How do I solve these problems?

解决方案

The first problem you can't solve.

The second problem is not anything to do with standard library classes. It's because you declare an instance of the class as a member of your own class.

Both problems are due to the requirement that the compiler must be able to find out the total size of a class from its definition.

However, the compiler can work out the size of a pointer to a class, even if it doesn't yet have the full definition of it. So a possible solution in such cases is to have a pointer (or reference) member in the consuming class.

Not much help in the base class case, because you won't get an 'is a' relationship.

Nor is it worth doing for something like std::string. Firstly, it's supposed to be a convenient wrapper around a character buffer, to save you from doing memory management on something so simple. If you then hold a pointer to it, just to avoid including the header, you're probably taking a good idea too far.

Secondly (as pointed out in a comment), std::string is a typedef to std::basic_string<char>. So you need to forward declare (and then use) that instead, by which time things are getting very obscure and hard to read, which is another kind of cost. Is it really worth it?

这篇关于向前声明基类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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