C++ 类在单独的文件中定义

C++ 类在单独的文件中定义,c++,C++,如果在文件B.cpp中定义了对象的类,是否可以在文件A.cpp中创建对象 我的意思是,您可以使用extern访问在另一个文件中初始化的变量。类是否有类似的定义?否。如果您实际实例化/使用该类,则当前翻译单元中的类定义必须对编译器可见 通常,您在头文件中有类的定义,该头文件将包含在需要使用该类的每个.cpp中。请注意,通常只声明类定义中的方法,因为它们的实现(定义)通常放在一个单独的.cpp文件中(除非您有内联方法,这些方法是在类定义中定义的) 但是请注意,如果您只需要声明/定义指向该类的指针,也

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


我的意思是,您可以使用extern访问在另一个文件中初始化的变量。类是否有类似的定义?

否。如果您实际实例化/使用该类,则当前翻译单元中的类定义必须对编译器可见

通常,您在头文件中有类的定义,该头文件将包含在需要使用该类的每个
.cpp
中。请注意,通常只声明类定义中的方法,因为它们的实现(定义)通常放在一个单独的
.cpp
文件中(除非您有
内联
方法,这些方法是在类定义中定义的)

但是请注意,如果您只需要声明/定义指向该类的指针,也就是说,如果编译器只需要知道,在您实际需要对该类执行操作之前,稍后将定义一个具有该名称的类型,那么只需要一个类声明(通常称为前向声明)就可以了(实例化类,调用其方法,…)。同样,这还不足以定义类类型的变量/成员,因为编译器必须至少知道类的大小,才能决定堆栈中另一个类/的内存布局

要回顾术语以及您可以/不能执行的操作:

// 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
类从某个接口继承),就可以使用工厂方法来实现相同的结果