结构体做函数参数与 const 使用场景
结构体做函数参数与 const 使用场景
结构体做函数参数,结构体中 const 使用场景。
结构体可以按值、按引用或按指针传给函数。大对象常用 const Student &s 避免拷贝,又承诺不修改;需要改成员时用非 const 引用或指针。成员也可加 const,如 const string name 表示创建后不可改。
GESP 四级爱考:值传参会不会改实参(不会)、引用传参会不会(会)、const 修饰参数或成员时的限制。120 分钟笔试里这类题多出现在单选,读清函数签名再判断。
void show(const Student &s) {
cout << s.name; // 只读,不能写 s.score
}
void bump(Student &s) { s.score++; }
参数列表里的 const 保护的是「这次调用别改我」;struct 成员上的 const 保护的是「这条记录某字段终身只读」。
在 C++ 中,如果希望通过函数修改传入的结构体对象的内容,应该使用哪种参数传递方式?
运行如下代码会输出( )。
struct Cat {
string name;
int age;
};
void birthday(Cat& c) {
c.age++;
}
int main() {
Cat kitty{"Mimi", 2};
birthday(kitty);
cout << kitty.name << " " << kitty.age;
}
执行下面代码后输出为( )。
struct S { int a; int b; };
void g(S s){ s.a += 10; }
void h(S& s){ s.b += 10; }
int main(){
S s{1,2};
g(s);
h(s);
cout << s.a << " " << s.b;
}