【发布时间】:2019-06-08 00:19:39
【问题描述】:
问题在于数组的声明。
我们可以评论
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <vector>
#include <list>
template <typename Type, size_t const SIZE>
class dummy_array {
Type data[SIZE] = {};
public:
dummy_array(){}
~dummy_array(){}
Type& operator[](size_t const index)
{
if (index < SIZE)
return data[index];
throw std::out_of_range("index out of range");
}
Type const& operator[](size_t const index) const
{
if (index < SIZE)
return data[index];
throw std::out_of_range("index out of range");
}
};
int main()
{
{
dummy_array<int, 6> arr();
arr[0] = 1;
arr[1] = 2;
for (int i = 0; i < 6; i++)
std::cout << arr[i] << " " ;
std::cout << std::endl;
}
return 0;
}
有人能解释一下为什么用“dummy_array arr();”声明吗?导致故障如下。 构建日志:
main.cpp: In function 'int main()':
main.cpp:34:12: error: pointer to a function used in arithmetic [-Wpointer-arith]
arr[0] = 1;
^
main.cpp:34:16: 错误:分配只读位置 '* arr'
arr[0] = 1;
^
main.cpp:35:12: 错误:指向算术中使用的函数的指针 [-Wpointer-arith]
arr[1] = 2;
^
main.cpp:35:16: 错误:分配只读位置 '*(arr + 1)'
arr[1] = 2;
^
main.cpp:38:27: 错误:指向算术中使用的函数的指针 [-Wpointer-arith]
std::cout << arr[i] << " " ;
^
【问题讨论】:
-
将
dummy_array<int, 6> arr();替换为dummy_array<int, 6> arr{};或只是dummy_array<int, 6> arr;,您可能会收到警告empty parentheses interpreted as a function declaration -
非常感谢。我得到了你的答案,因为编译器将其视为函数,并因违反对元素的访问而导致失败。