c++_结构体struct的使用

struct 在c中是结构体体,在c++ 中升级为class 了,他拥有类的全部特征。

不过和class 还是有区别的,struct成员包含的函数、变量默认都有public的访问权限。

#include <iostream>

struct ConfigModel {
    std::string model_path;
    bool is_rgb;
    int input_w;
    int input_h;
};

int main()
{
    //声明一个结构体,对结构体中的每个元素赋值
    ConfigModel config;
    config.model_path = "yolov5.onnx";
    config.is_rgb = false;
    config.input_w = 640;
    config.input_h = 640;

    //初始化,直接赋值
    ConfigModel config1 = { "yolov5.onnx" ,false,640,640 };

    //定义结构体数组
    ConfigModel configs[4] = {
        {"yolov5a.onnx" ,false,640,640},
        {"yolov5b.onnx" ,false,640,640},
        {"yolov5c.onnx" ,false,640,640},
        {"yolov5d.onnx" ,false,640,640}
    };


    //结构体整体赋值
    ConfigModel config2 = config1;
    std::cout << config2.model_path << std::endl;

    //结构体指针,用->来访问成员变量
    ConfigModel* cf = &config1;
    std::cout << cf->is_rgb << std::endl;
    //结构体数组的成员变量访问
    std::cout << configs[2].model_path << std::endl;

    //打印出结构体元素的地址
    printf("%p\n", &(configs[0].model_path));
    printf("%p\n", &(configs[0].is_rgb));
    std::cout << &(configs[0].input_w) << std::endl;
    std::cout << &(configs[0].input_h) << std::endl;

    system("pause");
    return 0;
}

C语言中结构体使用:struct ConfigModel config = {...}; 关键字struct不能漏,但在c++中,可以直接使用ConfigModel config来定义结构体变量。

typedef的用法:

struct ConfigModel {
    std::string model_path;
    bool is_rgb;
    int input_w;
    int input_h;
}config;

typedef struct ConfigModel2 {
    std::string model_path;
    bool is_rgb;
    int input_w;
    int input_h;
}CONFIG;

int main()
{
    config = { "yolov5a.onnx" ,false,640,640 };
    std::cout << config.model_path << std::endl;
    CONFIG config1 = { "yolov5b.onnx" ,false,640,640 };
    std::cout << config1.model_path << std::endl;

    system("pause");
    return 0;
}

在该例子中,config是struct ConfigModel声明的一个结构体变量,CONFIG是struct ConfigModel2的同义字,可以使用CONFIG来定义变量。

对于typedef struct ConfigModel{...}CONFIG,结构体类型名就相当于"struct 结构体名",在该例子中,CONFIG相当于struct ConfigModel的别名。

在C语言编程中是不允许在定义结构体变量时省略struct关键字,当然C++中用不用的结果都是一样的,所以有时候为了平台的兼容性以及代码更好的可读性,使用typedef关键字。

结构体数值清零

1.手动赋值为0,结构体定义之后,将每个成员都赋值为0。

struct MyStruct {
    int a;
    char b;
    float c;
};
 
struct MyStruct myStruct = { 0 };

2.使用memset函数,将结构体中的所有成员都赋值为0。

struct MyStruct myStruct;
 
memset(&myStruct, 0, sizeof(struct MyStruct));
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值