c++ - 从具有命名构造函数问题的基类继承

标签 c++

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;
}

最后一个函数没有按预期工作——打印出“mesh_type = hybrid”。我认为 当我继承基类时出了点问题。任何建议表示赞赏! 它。

最佳答案

两个主要问题:

为了像您尝试的那样使用多态基类,您必须使用引用、指针或智能指针。由于对象 m1m2m3MeshGeneration 类型的普通变量,它们永远不会真正成为一个DerivedMeshGeneration,无论最初创建的=右边的函数是什么。

DerivedMeshGeneration::CreateUnstrMesh()MeshGeneration::CreateUnstrMesh() 的功能相同,因此它从一开始就不会创建派生对象。

关于c++ - 从具有命名构造函数问题的基类继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5021774/

相关文章:

c++ - 使用时间单位模板返回 chrono::duration 的函数

c++ - 如何使用glslang

c++ - sleep_until 不适用于 MSVC 中的 steady_clock

c++ - 调用基类的构造函数时对 vtable 的 undefined reference

c++ - 错误 : ‘fuse_operations_compat2’ has no non-static data member named ‘readdir’

c++ - 为什么延长临时对象的生命周期不会导致中间临时对象的延长?

python - 如何在 Cython 中包装 C++ 仿函数

c++ - MPI 发送/接收 vector

c++ - shared_ptr 错误表达式必须有算术、枚举、指针

c++ - 使用CodeBlocks编译64位DLL会导致链接器错误