i couldn't figure it out why compiler show this "error: 'i' was not declared in this scope"

huangapple go评论64阅读模式
英文:

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 &#39;Array&lt;T&gt;::Array(T*, int)&#39;:
./6cf77951-ab9d-463e-86aa-763810936e52.cpp:20:18: error: &#39;i&#39; was not declared in this scope
      cout&lt;&lt;*(ptr+i)&lt;&lt;&quot; &quot;;

I was expecting it to print the elements of the array for every for loop iteration

#include &lt;iostream&gt;
using namespace std;

template &lt;typename T&gt; class Array {
private:
	T* ptr;
	int size;

public:
	Array(T arr[], int s);
	void print();
};

template &lt;typename T&gt; Array&lt;T&gt;::Array(T arr[], int s)
{
	ptr = new T
展开收缩
; size = s; for (int i = 0; i &lt; size; i++) ptr[i] = arr[i]; cout&lt;&lt;*(ptr+i)&lt;&lt;&quot; &quot;; } template &lt;typename T&gt; void Array&lt;T&gt;::print() { for (int i = 0; i &lt; size; i++) cout &lt;&lt; &quot; &quot; &lt;&lt; *(ptr + i); cout &lt;&lt; endl; } int main() { int arr[5] = { 1, 2, 3, 4, 5 }; Array&lt;int&gt; 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 &lt; size; i++)
     ptr[i] = arr[i];
     cout&lt;&lt;*(ptr+i)&lt;&lt;&quot; &quot;;

should be

for (int i = 0; i &lt; size; i++)
{
     ptr[i] = arr[i];
     cout&lt;&lt;*(ptr+i)&lt;&lt;&quot; &quot;;
}

答案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.

huangapple
  • 本文由 发表于 2023年1月9日 15:58:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/75054460.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定