抽象函数和可变参数列表 [英] Abstract functions and variable arguments list

查看:198
本文介绍了抽象函数和可变参数列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an abstract class an I like to know if it's possible to define an abstract function with variable arguments list?

如果可能,给我一个例子。 / p>

Give me an example if it's possible.

推荐答案

是的,原则上是可行的。
下面是一个例子。
您可以在此处查看输出。

Yes, it is possible in principle. An example follows below. You can see the output here.

同时阅读关于变量参数列表此处 here

Also read about variable arguments list here and here

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

这篇关于抽象函数和可变参数列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆