英文:
i couldn't figure it out why compiler show this "error: 'i' was not declared in this scope"
问题
我尝试使用类模板来打印数组的元素,但在名为array的类构造函数中出现错误,错误信息如下:
在构造函数 'Array<T>::Array(T*, int)' 中:
./6cf77951-ab9d-463e-86aa-763810936e52.cpp:20:18: 错误:'i' 在此作用域中未声明
cout<<*(ptr+i)<<" ";
我原本期望它在每次循环迭代中打印数组的元素,如下所示:
#include <iostream>
using namespace std;
template <typename T> class Array {
private:
T* ptr;
int size;
public:
Array(T arr[], int s);
void print();
};
template <typename T> Array<T>::Array(T arr[], int s)
{
ptr = new T展开收缩;
size = s;
for (int i = 0; i < size; i++)
ptr[i] = arr[i];
cout<<*(ptr+i)<<" ";
}
template <typename T> void Array<T>::print()
{
for (int i = 0; i < size; i++)
cout << " " << *(ptr + i);
cout << endl;
}
int main()
{
int arr[5] = { 1, 2, 3, 4, 5 };
Array<int> a(arr, 5);
a.print();
return 0;
}
英文:
I tried to print the elements of the array by using class templates but it shows error in the class constructor named array like this:
In constructor 'Array<T>::Array(T*, int)':
./6cf77951-ab9d-463e-86aa-763810936e52.cpp:20:18: error: 'i' was not declared in this scope
cout<<*(ptr+i)<<" ";
I was expecting it to print the elements of the array for every for loop iteration
#include <iostream>
using namespace std;
template <typename T> class Array {
private:
T* ptr;
int size;
public:
Array(T arr[], int s);
void print();
};
template <typename T> Array<T>::Array(T arr[], int s)
{
ptr = new T展开收缩;
size = s;
for (int i = 0; i < size; i++)
ptr[i] = arr[i];
cout<<*(ptr+i)<<" ";
}
template <typename T> void Array<T>::print()
{
for (int i = 0; i < size; i++)
cout << " " << *(ptr + i);
cout << endl;
}
int main()
{
int arr[5] = { 1, 2, 3, 4, 5 };
Array<int> a(arr, 5);
a.print();
return 0;
}
答案1
得分: 2
易犯的错误
for (int i = 0; i < size; i++)
{
ptr[i] = arr[i];
cout << *(ptr+i) << " ";
}
英文:
Easy mistake to make
for (int i = 0; i < size; i++)
ptr[i] = arr[i];
cout<<*(ptr+i)<<" ";
should be
for (int i = 0; i < size; i++)
{
ptr[i] = arr[i];
cout<<*(ptr+i)<<" ";
}
答案2
得分: 0
你的循环,在定义了i的情况下,只有一行"ptr[i] = arr[i];"。接下来的一行"cout<<*(ptr+i)<<";" 不再属于循环体,因此对i一无所知。你需要使用花括号来表示多行代码。
英文:
Your loop, where i is defined, only has the line "ptr[i] = arr[i];". The next line "cout<<*(ptr+i)<<" ";" is no longer part of the loop's body and thus does know nothing about i. You need the curly braces for multiple lines.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论