在单独的文件中定义的类

joh*_*ith 4 c++

如果在文件B.cpp中定义了它的类,是否可以在文件A.cpp中创建一个对象?

我的意思是,您可以使用extern访问在另一个文件中初始化的变量.课程有类似的东西吗?

Mat*_*lia 5

不可以.如果您实际实例化/使用该类,那么类定义必须对当前转换单元中的编译器可见.

通常,您在头文件中定义了类,该文件将包含在每个.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
Run Code Online (Sandbox Code Playgroud)