在单独的文件中定义的类
Class defined in separate file
如果在文件B.cpp中定义了对象的类,那么是否可以在文件A.cpp中创建对象?
我的意思是,您可以使用extern访问在另一个文件中初始化的变量。有类似的课程吗?
否。如果您实际实例化/使用该类,则该类定义必须对当前翻译单元中的编译器可见。
通常,类的定义位于头文件中,该头文件将包含在需要使用该类的每个.cpp
中。请注意,类定义中的方法通常只声明,因为它们的实现(定义)通常放在一个单独的.cpp
文件中(除非您有在类定义中定义的inline
方法)。
然而,请注意,如果您只需要声明/定义指向类的指针,即编译器需要知道的是,在您实际需要对具有该名称的类型执行某些操作(实例化类、调用其方法…)之前,稍后将定义该类型,则您可以只使用类声明(通常称为正向声明),这还不足以定义类类型的变量/成员,因为编译器至少必须知道类的大小才能决定堆栈中其他类的内存布局。
概括一下术语以及你能做什么/不能做什么:
// Class declaration ("forward declaration")
class MyClass;
// I can do this:
class AnotherClass
{
public:
// All the compiler needs to know here is that there's some type named MyClass
MyClass * ptr;
};
// (which, by the way, lets us use the PIMPL idiom)
// I *cannot* do this:
class YetAnotherClass
{
public:
// Compilation error
// The compiler knows nothing about MyClass, while it would need to know its
// size and if it has a default constructor
MyClass instance;
};
// Class definition (this can cohexist with the previous declaration)
class MyClass
{
private:
int aMember; // data member definition
public:
void AMethod(); // method declaration
void AnInlineMethod() // implicitly inline method definition
{
aMember=10;
}
};
// now you can do whatever you want with MyClass, since it's well-defined
如果你的意思是:
// B.cpp
class B { /* ... */ };
// A.cpp
B* b = new B();
然后不,因为你需要类定义(至少要知道它的大小)。
但是,只要您要与不透明的对象指针竞争,就可以使用工厂方法来实现相同的结果(例如,如果B
类继承自某个接口)。
相关文章:
- 告诉CMake链接到自定义文件夹中的Boost
- 通过cMake使用具有自定义文件扩展名的共享库
- 威纳派读取自定义文件或文件夹的所有访问权限
- 使用命令列表解析自定义文件
- 单独的类声明和方法定义文件问题
- Qt解析自定义文件格式
- 将单独的头文件和类定义文件链接到主函数文件 - G++ 返回重载"undefined reference to"构造函数
- FAT32和NTF中的自定义文件属性
- 如何在没有"fatal error: Wt/WApplication: No such file or directory"的情况下将wt安装到自定义文件夹中
- C++ while 循环在自定义文件结构中
- QT C 读取自定义文件结构
- gcc 是否有编译指示来定义文件类型/编译器
- C/C++ 中的跨平台自定义文件头
- 使用头文件和类定义文件时未解决的外部符号错误
- 将此c++代码分解为单独的类规范文件和函数定义文件
- 自定义文件类中fstream对象的生存期
- 如何使用BinaryReader类使用C#读取自定义文件(C++)
- 提供带有libjpeg的自定义文件IO
- C++模块定义文件头内联符号
- 错误:未定义文件中的第一个引用符号