千家信息网

如何使用c中变长参数

发表于:2025-11-07 作者:千家信息网编辑
千家信息网最后更新 2025年11月07日,本篇内容主要讲解"如何使用c中变长参数",感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习"如何使用c中变长参数"吧!1.使用模板中的变长参数函数声明#inclu
千家信息网最后更新 2025年11月07日如何使用c中变长参数

本篇内容主要讲解"如何使用c中变长参数",感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习"如何使用c中变长参数"吧!

1.使用模板中的变长参数函数声明

#include using namespace std;/*变长参数函数模板声明*/template void print(T... val);/*边界条件*/void print(void){cout<<"here end"<void print(T1 start, T2... var){cout<<"sizeof ... now is: "<

其中的声明其实是没什么用的,只是告诉使用者可以按照这样的格式使用,如果不做这个声明,只保留"边界条件"和"递归的特例化定义",这样虽然可行,但是未免会造成困惑

执行结果如下:

实际上,这个"变长"付出的代价还是很大的,要递归的实例出n个函数,最终再调用边界条件的函数。过程如下

2.使用va_list()函数实现变长参数列表

以一个矩阵自动识别维度的程序为例

arrayMat.h

#include#include#includeusing namespace std;typedef int dtype;class mat{public:        mat();        ~mat();        void set_dim(int dim);        void mat::set_mat_shape(int i,...);        int  get_dim();        int* get_mat_shape();        void print_shape();        dtype* make_mat();private:        int dim;        int *shape;        dtype *enterMat;};

arrayMat.cpp

#include"arrayMat.h"mat::mat(){}mat::~mat(){}int mat::get_dim() {        return this->dim;}int * mat::get_mat_shape() {        return this->shape;}void mat::print_shape(){        for (int a = 0; a < this->dim; a++) {                std::cout << shape[a] << " " ;        }}void mat::set_dim(int i) {        this->dim = i;}void mat::set_mat_shape(int i, ...) {        va_list _var_list;        va_start(_var_list, i);        int count = 0;        int *temp=new int[100];        while (i != -1) {                //cout << i <<" ";                temp[count] = i;                count++;                i = va_arg(_var_list, int);        }        va_end(_var_list);        this->set_dim(count);        this->shape = temp;        //std::cout << std::endl;        //this->shape = new int [count];        //for (int j = 0; j < count; j++)                //shape[j] = temp[j];}//Mat2D A[i][j] = B[i + j * rows]

main.cpp

#include"arrayMat.h"int main() {        mat m1,m2;        m1.set_mat_shape(1,3,128,128,-1);        int *shape = m1.get_mat_shape();        int dim = m1.get_dim();        cout << "dim: " << dim<

运行结果:

到此,相信大家对"如何使用c中变长参数"有了更深的了解,不妨来实际操作一番吧!这里是网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

0