首页 > 解决方案 > 在 C++ 中定义数组并在 struct 中使用它

问题描述

我想在头文件中定义字符数组:

#define name char[5]

然后在结构中使用这个定义,如下所示:

struct dog{
    name nameOfDog;
    int  ageOfDog;
};

但这使我出现以下错误:

"Brackets are not allowed here; to declare an array, place the brackets after the name"

还有另一种方法可以将其设置为正确的语法吗?

谢谢!

标签: c++arrays

解决方案


对于 C++ 中的数组,使用 std::array

#include <array>
#include <string>

struct dog
{
   std::array<char,5> name;
   unsigned int age;
};

std::string a_string{"Hello"};

对于名称,我不会使用数组,但我会使用 std::string


推荐阅读