c ++在非纯虚函数中使用纯虚函数的抽象类

时间:2013-09-11 03:08:01

标签: c++ abstract-class pure-virtual

我想创建一个抽象类,它具有纯虚函数,由非纯虚构造函数调用。以下是我的档案class.hpp

#ifndef __CLASS_HPP__
#define __CLASS_HPP__

#include <iostream>

class Parent {
 public:
  Parent(){
    helloWorld(); // forced to say hello when constructor called                    
  };
  virtual void helloWorld() = 0; // no standard hello...                            
};

class Child : public Parent {
 public:
  void helloWorld(){ // childs implementation of helloWorld                         
    std::cout << "Hello, World!\n";
  };
};

#endif

在这个例子中,我有一个具有纯虚函数helloWorld()的父类。我希望每个派生类在调用构造函数时都说“hello”;因此helloWorld()在父类构造函数中的原因。但是,我希望每个派生类都被强制选择它会如何说“你好”,而不是使用默认方法。这可能吗?如果我尝试使用g ++编译它,我会得到构造函数调用纯虚函数的错误。我的main.cpp是:

#include "class.hpp"

int main(){
  Child c;
  return 0;
}

我正在使用g++ main.cpp -o main.out进行编译,结果错误是:

In file included from main.cpp:1:0:
class.hpp: In constructor ‘Parent::Parent()’:  
class.hpp:9:16: warning: pure virtual ‘virtual void Parent::helloWorld()’ called from constructor [enabled by default]

有关如何以合法方式获得类似设置的任何建议吗?

新问题

DyP引起了我的注意,构造函数不使用任何被覆盖的函数,所以我想要做的就是设置它的方式是不可能的。但是,我仍然想强制任何派生的构造函数调用函数helloWorld(),有没有办法做到这一点?

2 个答案:

答案 0 :(得分:2)

你在做什么是非法的。

为了在C ++中定义抽象类,您的类必须至少有一个纯虚函数。在你的情况下

virtual void helloWorld() = 0;

在这种情况下你是对的。

但是你的纯虚函数没有任何实现,因为它是纯虚函数。因此,从同一类的constuructor调用纯虚函数是违法的。(在类级纯虚函数中没有任何实现)

所以,

Parent(){
helloWorld(); // forced to say hello when constructor called                    
};

这是非法的。

如果需要,可以在派生类中实现纯虚函数,然后从派生类的构造函数中调用helloWorld()

答案 1 :(得分:1)

为什么不简单地将它添加到每个子类的构造函数中?

如果你想避免每次在构造函数中编写它(甚至跳过或继承它),那么你可以使用CRTP:

class Parent {
 public:
  Parent(){};
  virtual void helloWorld() = 0; // no standard hello...                            
};

template <typename Par>
class ParentCRTP: public Parent {
 public:
  ParentCRTP(){
    Par::doHelloWorld();
  };
  virtual void helloWorld(){
    Par::doHelloWorld();
  }
};

class Child : public ParentCRTP<Child> {
 public:
  static void doHelloWorld(){ // childs implementation of helloWorld                         
    std::cout << "Hello, World!\n";
  };
};

这种方法不会给你孩子的hello方法中的子类指针 - 此时类实例只有Parent实例,不能获得有效的Child指针。要在构造后强制执行Child的方法,您只能使用两阶段初始化:首先使用构造函数创建类实例,然后使用单独的方法初始化它。

除此之外,像这样的问题可能是重新思考你的设计的暗示。你不应该强迫你的类以给定的方式初始化自己。