在单独的文件中定义的类

Class defined in separate file

本文关键字:定义 文件 单独      更新时间:2023-10-16

如果在文件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类继承自某个接口)。