2011-02-16 83 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();