c++结构体传参

复制代码
//
// Created by 徐昌真 on 2024/10/5.
//
#include <iostream>
using namespace std;

//定义一个结构体
struct Circle{
    int x, y, r;
};

//定义一个可以修改结构体内容的函数
void movePoint(Circle c, int x, int y){
    c.x += x;
    c.y += y;
}

//定义一个可以输出结构体内容的函数
void printCircle(Circle c){
    cout << '(' << c.x << ',' << c.y << ") " << c.r << endl;
}

int main() {

    //创建一个结构体
    Circle c = {1,2,3};
    //调用修改结构体的函数
    movePoint(c,1,2);
    //调用输出结构体的函数
    printCircle(c);

    return 0;
}

我们这样子写完之后 会发现修改的结果并没有生效 这是因为值的改变只在函数的内部 并没有在main函数内部改变 我们需要用指针 在地址里面修改值 才可以

这是输出结果

这是修改后的代码

复制代码
//
// Created by 徐昌真 on 2024/10/5.
//
#include <iostream>
using namespace std;

//定义一个结构体
struct Circle{
    int x, y, r;
};

//定义一个可以修改结构体内容的函数
void movePoint(Circle* c, int x, int y){
    c->x += x;
    c->y += y;
}

//定义一个可以输出结构体内容的函数
void printCircle(Circle c){
    cout << '(' << c.x << ',' << c.y << ") " << c.r << endl;
}

int main() {

    //创建一个结构体
    Circle d = {1,2,3};
    //调用修改结构体的函数
    movePoint(&d,1,2);
    //调用输出结构体的函数
    printCircle(d);

    return 0;
}

我们只需传入指针类型的数据即可

相关推荐
Drone_xjw3 小时前
Qt国际化多语言配置详解-入门到精通
开发语言·qt·命令模式
爱吃提升3 小时前
Python 多线程 threading + 多进程 multiprocessing 完整实操教程
开发语言·python
不会C语言的男孩3 小时前
C++ Primer 第18章:用于大型程序的工具
开发语言·c++
星恒随风3 小时前
C++ 类和对象入门(三):拷贝构造、赋值运算符重载和深浅拷贝
开发语言·c++·笔记·学习
Cx330❀3 小时前
【MySQL基础】库与表的全面操纵指南
linux·服务器·网络·数据库·c++·mysql
RickyWasYoung3 小时前
【Matlab】科研绘图配色-极简版
开发语言·matlab
凡人叶枫3 小时前
Effective C++ 条款03:尽可能使用 const
linux·开发语言·c++·嵌入式开发
光影6273 小时前
Python接口自动化测试----Requests库基础入门
开发语言·python·测试工具·pycharm·自动化
程序媛_3 小时前
【Python】连接PostgreSQL获取手机验证码
开发语言·python·postgresql
ch.ju3 小时前
Java Programming Chapter 4——Inherited call
java·开发语言