在函数内处理结构体对外部结构体有影响吗
时间: 2024-03-24 10:32:56 浏览: 15
函数内部处理结构体不会对外部结构体产生影响,因为在C++中,结构体是一种值类型,传递给函数时会进行复制,函数内部对结构体的修改不会影响到原始结构体。如果需要在函数内部修改原始结构体,可以将结构体的指针作为参数传递给函数,或者使用引用传递。以下是两种方法的示例代码:
1.使用指针传递结构体:
```cpp
#include <iostream>
using namespace std;
struct Student {
string name;
int age;
};
void changeAge(Student* s, int newAge) {
s->age = newAge;
}
int main() {
Student s = {"Tom", 18};
changeAge(&s, 20);
cout << s.age << endl; // 输出:20
return 0;
}
```
2.使用引用传递结构体:
```cpp
#include <iostream>
using namespace std;
struct Student {
string name;
int age;
};
void changeAge(Student& s, int newAge) {
s.age = newAge;
}
int main() {
Student s = {"Tom", 18};
changeAge(s, 20);
cout << s.age << endl; // 输出:20
return 0;
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)