【问题标题】:Abstract functions and variable arguments list抽象函数和变量参数列表
【发布时间】:2012-02-21 11:35:07
【问题描述】:

我有一个抽象类,我想知道是否可以用可变参数列表定义一个抽象函数?

如果可能的话,给我一个例子。

【问题讨论】:

  • 请添加一个您想做的简单伪代码示例。

标签: c++ function abstract variadic-functions


【解决方案1】:

是的,原则上是可以的。 下面是一个示例。 可以看到输出here

另请阅读变量参数列表herehere

#include <iostream>
#include <cstdarg>

using namespace std;


class AbstractClass{

public:

  virtual double average(int num, ... ) = 0;


};


class ConcreteClass : public AbstractClass{
public:

   virtual double average(int num, ... ) 
   {
      va_list arguments;                     // A place to store the list of arguments
      double sum = 0;

      va_start ( arguments, num );           // Initializing arguments to store all values after num
      for ( int x = 0; x < num; x++ )        // Loop until all numbers are added
        sum += va_arg ( arguments, double ); // Adds the next value in argument list to sum.
      va_end ( arguments );                  // Cleans up the list

      return sum / num;                      // Returns the average
  }



};



int main()
{
    AbstractClass* interface = new ConcreteClass();
    cout << interface->average( 3 , 20 ,30 , 40 );

    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-30
    • 1970-01-01
    • 2013-08-02
    相关资源
    最近更新 更多