未使用的变量禁止打印?

Unused Variable prohibits print?

本文关键字:打印 禁止 变量 未使用      更新时间:2023-10-16

我不确定为什么我的函数不起作用。它应该打印出一些东西(用户越界后的错误消息)我已经将数组索引设置为 3 个索引槽。我还收到一个错误"未使用的变量'您的数组',我不确定从这里开始。仍在尝试学习C ++,因此,建议或帮助将不胜感激。

#include <iostream>
using namespace std;
class safeArray{
public:
void outofBounds(int,int);
int yourArray[3];
int i;
};
void outofBounds(int,int);
int yourArray[3];
int i;
void outofBounds(int yourArray[],int sizeofArray) {       
for (i=0;i<sizeofArray;i++){
cout<<"Please enter integer";
cin >>yourArray[i];
yourArray[i]++;
for (i=0;i>sizeofArray;){
cout<<"safeArray yourArray (" <<yourArray[0]<<","<<yourArray[3]<<")"
<<endl;
}}}
int main() {
void outofBounds(int,int);
int yourArray[3];    //Error: Used variable "yourArray"
};

您的程序运行良好。除非您将"-Werror"标志添加到编译器,否则会将"未使用的变量"-警告视为错误。 代码编译良好,如下所示:http://coliru.stacked-crooked.com/a/d648b94f205b51dc

尽管您的程序没有执行您希望它执行的操作,原因如下:


1.) 在不同的命名空间中,您有 3 个越界的重新定义:

  • 一个在类命名空间安全数组内,它是一个成员函数 的它
  • 然后在全球空间内
  • 然后在主函数内部(入口点)

但实际定义的是全局空间中的那个(第二个)


2.) 您没有将任何内容传递给 main 内部的函数。 首先在那里定义你的数组,然后通过执行以下操作调用函数:

int yourArray[3];
outofBounds(yourArray, 3);

3.) 您可能希望在 SafeArray 类中定义成员方法"OutofBounds"。这可以通过编写 scope 运算符:: 来完成,该运算符指定成员函数所属的类:

class SafeArray {   // is a class, can also be struct since everything is public anyways
public:
void outofBounds(int,int); // a member of the class SafeArray
// private:
int yourArray[3];
int i;
};
void SafeArray::outofBounds(int yourArray[],int sizeofArray) { 
// do something...
}

但话又说回来,你需要一些构造函数来初始化类的成员。需要做一些工作才能使其工作,就像你想要的那样。祝你好运:)