Inherit from Base class with named constructors problems
class MeshGeneration{
public:
static MeshGeneration CreateUnstrMesh() {
cout<<"Unstr call开发者_Python百科ed"<<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;
}
The last function is not working as expected--print out "mesh_type = hybrid". And I think something is wrong when I inherit the base class. Any suggestions are appreciated! it.
Two major problems:
In order to use a polymorphic base class like you're attempting, you must use a reference, pointer, or smart pointer. Since the objects m1
, m2
, and m3
are plain variables of type MeshGeneration
, they will never really be a DerivedMeshGeneration
, no matter what the function to the right of the =
originally created.
DerivedMeshGeneration::CreateUnstrMesh()
is the same function as MeshGeneration::CreateUnstrMesh()
, so it never creates a derived object in the first place.
Here your code prints:
Unstr called
mesh_type = unstructured
Str called!
mesh_type = structured
Unstr called
mesh_type = unstructured
and it is what it should happen.
m1
, m2
and m3
are objects of type MeshGeneration
, and MeshGeneration::CreateHybridMesh
does not print anything.
In order to print mesh_type = hybrid
you should have an object of type DerivedMeshGeneration
(or a pointer/reference to a DerivedMeshGeneration
or a MeshGeneration
pointing/referencing to an instance of DerivedMeshGeneration
).
In this line:
MeshGeneration m3 = DerivedMeshGeneration::CreateUnstrMesh();
You are making a copy of the return value of DerivedMeshGeneration::CreateUnstrMesh(), and that copy is of type MeshGeneration. Thus the function that gets called is the one in MeshGeneration.
You should be using pointers or references instead.
The problem is
DerivedMeshGeneration::CreateUnstrMesh()
doesn't create an instance of DerivedMeshGeneration
, rather it creates an instance of MeshGeneration
.
Thanks guys. Now this works as I expected:
DerivedMeshGeneration * m3 = new DerivedMeshGeneration;
m3->CreateHybridMesh();
精彩评论