【问题标题】:Abstract class as argument (interface case)抽象类作为参数(接口案例)
【发布时间】:2013-03-25 12:58:06
【问题描述】:

我有一个抽象类应该是一个接口,像这样:

  class IDataSource
    {
    public:
        virtual double getMeThatDouble() = 0;
    }

还有一些实现,比如

 class IDataSourceStreamer
    {
    public:
        double getMeThatDouble()
          {
            //implementation
          }
    }

关键是我想将它用作其他类的构造函数中的初始参数,例如

class DataNeeder
{
  public:
       explicit DataNeeder(IDataSource);
}

麻烦来了 - "parameter of abstract class type is not allowed"

我知道出于特殊原因禁止使用抽象类本身是不可能的。所以我该怎么做?是像

这样的方法吗
IDataSource.FeedThat(DataNeeder)

唯一的选择?有点丑。

【问题讨论】:

    标签: c++ interface abstract-class


    【解决方案1】:

    您需要将抽象类型作为引用或指针传递。例如:

    class DataNeeder {
    public:
        explicit DataNeeder(IDataSource &source) : source_(source) {
        }
    
        void someMethod() {
            double x = source_.getMeThatDouble();
            // ...
        }
    
    private:
        IDataSource &source_;
    }
    

    然后你可以让DataNeeder 的成员函数在source_ 上运行。正如我所提到的,你也可以使用指针来完成这个任务,但我喜欢只使用指针来表示“OUT”参数和可以想象为NULL的东西。

    【讨论】:

      猜你喜欢
      • 2014-08-27
      • 1970-01-01
      • 2017-03-09
      • 2016-04-19
      • 2011-05-22
      • 1970-01-01
      • 2014-08-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多