声明一个C ++类,而不在当前翻译单元中定义它 [英] Declare a C++ class without defining it in the current translation unit

查看:320
本文介绍了声明一个C ++类,而不在当前翻译单元中定义它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有可能声明一个类而不定义它(向前声明),只要稍后在翻译单元中定义它。在函数的情况下,可以声明一个函数,而不在翻译单元中定义它,并且链接器将链接到它在不同翻译单元中的定义。是否可以做类同样的声明?

It is possible to declare a class without defining it (forward declaration) as long as it is defined later on within the translation unit. In the case of functions, one can declare a function without defining it within the translation unit, and the linker will link it to its definition in a different translation unit. Is it possible to do the same with class declarations?

(如果这是不可能的,有没有用于在当前TL中没有定义的前向声明类,一个错误?)

(if this is not possible, is there any use to a forwardly declared class without a definition in the current TL, or is that always an error?)

这样,除非这不编译:

mymain.cpp: / p>

mymain.cpp:

class myclass; // declare without defining

myclass::myclass();
void myclass::barf();

int main() {
  myclass *m = new myclass();
  m->barf();
  return 0;
}

myclass.cpp:

myclass.cpp:

#include <iostream>

class myclass { // define the implementation
public:
    myclass();
    void barf();
};

myclass::myclass() { } //empty constructor
void myclass::barf() {
    std::cout << "barfing\n";
}


推荐答案

声明一个类,但只能使用指向前向声明的类的指针和引用。你不能使用前向声明类的实际对象,因为编译器不够了解它;特别是它不知道对象有多大或它的成员是什么。尝试转发声明成员函数(如你所做的)不会工作,因为前向声明的语法不允许您指定函数是虚拟还是非虚拟(或者可能继承自一些基类)。

It is possible to forward-declare a class, but only pointers and references to forward-declared classes can be used. You can't use an actual object of a forward-declared class because the compiler doesn't know enough about it; in particular it doesn't know how large the object is or what its members are. Trying to forward-declare member functions (as you have done) won't work because the syntax of the forward declaration doesn't allow you to specify whether the functions are virtual or non-virtual (or perhaps inherited from some base class).

在源文件中转发声明一个类通常并不常用,但它在头文件中很有用。特别地,通常在库的公共头文件中转发声明一个类,并使用指向该类型的指针作为不透明句柄。类定义对于库是私有的,但是用户代码可以传递指向该类的对象的指针,而不知道类的实现是什么样子。当指针是智能指针时,这种方法尤其有效。

It is not often useful to forward-declare a class in a source file, but it can be useful in a header file. In particular it's common to forward-declare a class in a library's public header file and use pointers to that type as opaque handles. The class definition remains private to the library but user code can pass around pointers to objects of that class without ever knowing what the class's implementation looks like. This works particularly well when the pointers are smart pointers.

这篇关于声明一个C ++类,而不在当前翻译单元中定义它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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