【发布时间】:2021-06-04 10:47:27
【问题描述】:
我可以在 C++ 中将整数数组定义为结构中的属性吗?
我就是这样尝试的,输出也贴出来了:
struct SpaceTime{
SpaceTime(int Coordinates[2][2]):
Coordinates_(Coordinates[2][2]){}
public:
int Coordinates_;
};
int main(){
SpaceTime earth({{100,200},{300,400}});
std::cout << earth.Coordinates_[1][1] << std::endl;
}
来自 C++14、Windows 10 Visual Studio 的输出:
.\StackOverFlow.cpp: In function 'int main()':
.\StackOverFlow.cpp:28:39: error: no matching function for call to 'SpaceTime::SpaceTime(<brace-enclosed initializer list>)'
SpaceTime earth({{100,200},{300,400}});
^
.\StackOverFlow.cpp:22:5: note: candidate: SpaceTime::SpaceTime(int (*)[2])
SpaceTime(int Coordinates[2][2]):
^~~~~~~~~
.\StackOverFlow.cpp:22:5: note: no known conversion for argument 1 from '<brace-enclosed initializer list>' to 'int (*)[2]'
.\StackOverFlow.cpp:21:8: note: candidate: constexpr SpaceTime::SpaceTime(const SpaceTime&)
struct SpaceTime{
^~~~~~~~~
.\StackOverFlow.cpp:21:8: note: no known conversion for argument 1 from '<brace-enclosed initializer list>' to 'const SpaceTime&'
.\StackOverFlow.cpp:21:8: note: candidate: constexpr SpaceTime::SpaceTime(SpaceTime&&)
.\StackOverFlow.cpp:21:8: note: no known conversion for argument 1 from '<brace-enclosed initializer list>' to 'SpaceTime&&'
.\StackOverFlow.cpp:29:35: error: invalid types 'int[int]' for array subscript
std::cout << earth.Coordinates_[1][1] << std::endl;
【问题讨论】:
-
"...does not work..." 无法清楚地描述您遇到的问题。请发布 - 什么不起作用以及为什么。
-
为什么要有构造函数,因为内置的初始化会起作用?
struct ST{int c[2][2];}; int main(){ auto earth = ST{{{100, 200}, {300, 400}}};... -
或更简单的:
ST earth{ {100, 200}, {300, 400} }; -
我不清楚你问的是哪个方面。 “结构中的属性”表示结构的成员,如
SpaceTime::Coordinates_? (但您没有尝试将Coordinates_定义为数组,只是用数组对其进行初始化。)还有一个问题是您看到的整数数组是什么——来自例如 Javascript 的人可能会看到 @ 987654327@ 作为一个数组,当它是一个初始化列表时。您能否添加更多文字来描述您对情况的理解以及促使您以这种方式编写代码的原因? -
如果你想要一个灵活的数组——c++ 不支持它。 C 确实。但是你写的这些东西无论如何都行不通。
标签: c++ arrays data-structures struct attributes