本文建议在看完“C++中的数组函数”后食用。
结构体在某种程度上与数组有一定的相似性,就是能够包含较多的元素。不过结构体与数组相比起来,其整体性更强。整体性强的表现主要体现在一个结构体变量可以直接赋值给另一个结构体变量,就如同基本变量之间可以互相赋值一样,该表现显然与数组截然不同。该“整体性”也表明了,结构体完全可以像基本变量一样在函数调用的时候采取值传递的方式进行工作,即复制一份自己的拷贝结构体变量,令其代替自己进入函数干活。
以下代码为结构体函数的第一种使用方法,即传递与返回结构体。该结构体函数的写法与基本变量函数的写法大体相同:
#include <iostream>
struct exampleStructure
{
int variable1;
int variable2;
};
exampleStructure sum(exampleStructure a,exampleStructure b);
int main()
{
using namespace std;
exampleStructure A={12,13};//结构体变量A
exampleStructure B={14,15};//结构体变量B
exampleStructure addNum=sum(A,B);
cout<<"total variable1:"<<addNum.variable1<<endl;//打印出variable1的和
cout<<"total variable2:"<<addNum.variable2<<endl;//打印出variable2的和
cin.get();//按一个按键后退出
return 0;
}
exampleStructure sum(exampleStructure a,exampleStructure b)
{
exampleStructure total;
total.variable1=a.variable1+b.variable1;
total.variable2=a.variable2+b.variable2;
return total;
}
以上的代码实现了两个结构体变量的子成员相加。以上代码可以自行脑补:如果将exampleStructure 代替为某个基本变量,整个程序的写法与构造与基本变量函数区别甚小。传递与返回结构体方法中,调用的函数sum()内生成2个参量结构体a与b,两个参量结构体分别拷贝参数结构体A与B的内容,随后在函数中工作。
这种值传递的方法有一个明显缺点:结构体与基本变量也有本质的不同,在一些大型项目中结构体往往会拥有较多成员,值传递时拷贝内容,对内存的需求更大,会降低程序的运行速度。
好在结构体还配套了结构体指针这个神奇的工具。传递内容嫌麻烦,那我们传递地址不就好了。在将上块结构体函数改成结构体指针函数有以下需要注意的地方:
1.与数组名称是数组第一个元素的地址不同,结构体的名称只是个名字,如果想得到结构体的地址,那么必须使用地址运算符&。因此调用函数时需要将结构体的地址(&A)传递进去而不是将本身(A)传递进去。
2.函数中的形参为一个结构体指针(*a),如果函数不需要修改内容,则应加入const修饰符防止内容被修改。
3.函数中的形参是结构体指针,结构体指针调用变量应用符号->。
以下为修改后的“结构体指针”函数。
#include <iostream>
struct exampleStructure
{
int variable1;
int variable2;
};
exampleStructure sum(const exampleStructure *a,const exampleStructure *b);
int main()
{
using namespace std;
exampleStructure A={12,13};//结构体变量A
exampleStructure B={14,15};//结构体变量B
exampleStructure addNum=sum(&A,&B);
cout<<"total variable1:"<<addNum.variable1<<endl;//打印出variable1的和
cout<<"total variable2:"<<addNum.variable2<<endl;//打印出variable2的和
cin.get();//按一个按键后退出
return 0;
}
exampleStructure sum(const exampleStructure *a,const exampleStructure *b)
{
exampleStructure total;
total.variable1=a->variable1+b->variable1;
total.variable2=a->variable2+b->variable2;
return total;
}
这样用指针还不过瘾,我将“结构体指针”函数又修改成了“结构体指针”指针函数,但是好像还不如“结构体指针”函数来的简单,以下是修改后的代码:
#include <iostream>
struct exampleStructure
{
int variable1;
int variable2;
};
exampleStructure *sum(const exampleStructure *a,const exampleStructure *b);
exampleStructure *sum(const exampleStructure *a,const exampleStructure *b)
{
exampleStructure add;
exampleStructure *total=&add;
total->variable1=a->variable1+b->variable1;
total->variable2=a->variable2+b->variable2;
return total;
}
int main()
{
using namespace std;
exampleStructure A={12,13};//结构体变量A
exampleStructure B={14,15};//结构体变量B
exampleStructure *addNum=sum(&A,&B);
cout<<"total variable1:"<<addNum->variable1<<" total variable2:"<<addNum->variable2<<endl;//打印出variable1与varaible2的和
cin.get();//按一个按键后退出
return 0;
}
矩阵论老师说,如果总是想着用小窍门和奇思妙想来解决问题,往往说明你没有掌握更高级的方法。在C++中提出了新的复合类型——引用变量,可以方便解决参数数据大的问题。下一节将仔细说明引用与结构体函数的使用方法。