2011-02-16 82 views
1
class MeshGeneration{ 
    public: 
     static MeshGeneration CreateUnstrMesh() { 
      cout<<"Unstr called"<<endl; 
      return MeshGeneration(0);} 
     static MeshGeneration CreateStrMesh() { 
      cout<<"Str called!"<<endl; 
      return MeshGeneration(1);} 
     virtual void CreateHybridMesh(){} 
    protected: 
     MeshGeneration(int mesh_type = -1){ 
      string mstring; 
      if(mesh_type == 0) 
      mstring = "unstructured"; 
      else if(mesh_type == 1) 
      mstring = "structured"; 
      else; 
      cout <<"mesh_type = "<<mstring<<endl; 
     } 
}; 
class DerivedMeshGeneration:public MeshGeneration{ 
    public: 
    void CreateHybridMesh(){ 
     cout<<"mesh_type = hybrid"<<endl; 
    } 
}; 

int main(int argc, char * argcv[]){ 
    MeshGeneration m1 = MeshGeneration::CreateUnstrMesh(); 
    MeshGeneration m2 = MeshGeneration::CreateStrMesh(); 
    MeshGeneration m3 = DerivedMeshGeneration::CreateUnstrMesh(); 
    m3.CreateHybridMesh(); // not working as expected.. 
    return 0; 
} 

最後的功能無法正常工作。我認爲 當我繼承基類時有些事情是錯誤的。任何建議表示讚賞! 吧。繼承基類的構造函數命名問題

回答

4

兩個主要問題:

爲了使用多態基類,就像你嘗試,你必須使用一個參考,指針或智能指針。由於對象m1,m2m3是類型爲MeshGeneration的普通變量,因此它們絕不會是DerivedMeshGeneration,無論最初創建的=的權利如何。

DerivedMeshGeneration::CreateUnstrMesh()MeshGeneration::CreateUnstrMesh()功能相同,所以它從不創建派生對象。

+0

謝謝。我嘗試了「DerivedMeshGeneration m3 = DerivedMeshGeneration :: CreateUnstrMesh();」,當我編譯時,我得到了錯誤消息,如「錯誤:從'MeshGeneration'轉換爲非標量類型'DerivedMeshGeneration'請求」,對此的任何建議? – stonebird 2011-02-16 20:49:02

+0

@ user606769:DerivedMeshGeneration :: CreateUnstrMesh()的返回類型仍然是`MeshGeneration`,因爲它是基類中的函數。而且,您不能將基類類型的對象分配給派生類類型的對象。 – Xeo 2011-02-16 22:29:45

2

下面的代碼打印:

Unstr called 
mesh_type = unstructured 
Str called! 
mesh_type = structured 
Unstr called 
mesh_type = unstructured 

,這是應該發生的事情。

m1m2m3MeshGeneration類型的對象,而MeshGeneration::CreateHybridMesh不打印任何東西。

爲了打印mesh_type = hybrid你應該有DerivedMeshGeneration類型的對象(或指針/參照DerivedMeshGenerationMeshGeneration指點/引用到的DerivedMeshGeneration一個實例)。

1

在這一行:

MeshGeneration m3 = DerivedMeshGeneration::CreateUnstrMesh(); 

您正在DerivedMeshGeneration的返回值的副本:: CreateUnstrMesh(),和副本類型MeshGeneration的。因此被調用的函數是MeshGeneration中的函數。

您應該改用指針或引用。

1

問題是

DerivedMeshGeneration::CreateUnstrMesh() 

不創建的DerivedMeshGeneration一個實例,而它創造的MeshGeneration一個實例。

1

謝謝你們。現在,這工作正如我所料:

DerivedMeshGeneration * m3 = new DerivedMeshGeneration;

m3-> CreateHybridMesh();