这些上机实验在Qt5.9上完成的,具体步骤
- 结构体引用
#include <iostream> #include<stdlib.h> using namespace std; struct mycoach { string name; int age; }; void *addcoachinfo(mycoach * &cpc,string name,int age) { cpc=(mycoach*)malloc(sizeof(mycoach)); cpc->name=name; cpc->age=age; cout<<"大家好我是"<<cpc->name<<"今年芳龄"<<cpc->age<<endl; free(cpc); cpc=NULL; } int main() { mycoach *cpc=NULL; addcoachinfo(cpc,"陈培昌",22); return 0; }
- 引用分为普通引用和常引用
int main() { int a=10; int &aa =a; aa=88; printf("%d\n",aa); return 0; }
常引用的目的往往是不希望被修改
引用实际上是内存的别名,由于字面量没有地址,因此第9行的代码有误
正确的做法是第10行
函数中常引用,目的是让实际参数只拥有只读属性
- 对指针的引用
#include <iostream> using namespace std; struct mycoach { string name; int age; }; int main() { mycoach *cpc = (mycoach*)malloc(sizeof(mycoach)); cpc->name="陈培昌"; mycoach * &wr=cpc; wr->name="魏锐"; cout <<cpc->name<< endl; return 0; }
- 对比:常量引用
#include <iostream> using namespace std; struct mycoach { string name; int age; }; void showinfo(const mycoach &cpc) { //cpc.name="中国队长";如果去掉注释就报错,常量不可修改 cout<<"hello! I'm"<<cpc.name<<endl; } int main() { mycoach *cpc = (mycoach*)malloc(sizeof(mycoach)); cpc->name="陈培昌"; const mycoach &wr=*cpc;//常量引用只能引用字面量 showinfo(wr); return 0; }