如何使用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: "< 

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

执行结果如下:

如何使用c中变长参数

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

如何使用c中变长参数

如何使用c中变长参数

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

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

arrayMat.h

#include
#include
#include
using 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中变长参数

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


文章标题:如何使用c中变长参数
链接分享:http://lszwz.com/article/gpghii.html

其他资讯

售后响应及时

7×24小时客服热线

数据备份

更安全、更高效、更稳定

价格公道精准

项目经理精准报价不弄虚作假

合作无风险

重合同讲信誉,无效全额退款