2011-06-28 45 views
4

如果文件A.cpp中的對象在文件B.cpp中定義,是否可以創建一個對象?在單獨文件中定義的類

我的意思是,你可以使用extern來訪問在另一個文件中初始化的變量。有什麼類似的類嗎?

回答

5

否。如果實際實例化/使用該類,那麼類定義對於當前編譯器中的編譯器必須是可見的。

通常情況下,您將在每個需要使用該類的.cpp中包含的頭文件中定義該類。請注意,通常是一個類定義方法僅宣佈,因爲它們的實現(定義)通常放在一個單獨的文件.cpp(除非你有inline方法,屬於類定義中定義)。

注意然而,你可以只用一個類聲明(通常稱爲向前聲明),如果你需要的是申報/定義指針類脫身 - 如果所有的編譯器需要知道IE是一個類型在實際需要對其進行操作之前,會定義該名稱(實例化該類,調用其方法,...)。再次,這是而不是足以定義該類的變量/成員,因爲編譯器必須至少知道該類的大小來決定其他類/堆棧的內存佈局。

回顧一下有關的術語和有關您可以/不可以做什麼:

// 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 
2

如果你的意思是這樣的:

// B.cpp 
class B { /* ... */ }; 

// A.cpp 
B* b = new B(); 

然後沒有,因爲你需要的類定義(要知道它的大小至少)。

但是可以使用工廠方法來實現相同的效果,只要你是有不透明對象指針抗衡(例如如果該B類從一些接口繼承)。

相關問題