我遇到的问题是当我尝试在3个类对象的数组中设置一些类变量时,我得到一个错误,指出函数所需的变量未在main函数的范围内声明
我仍然是新手,并将我的界面与我的实现分开,我觉得它有时会让人感到困惑。
我一直在查看本网站和其他网站上的其他一些示例,我无法确切地知道我的问题是什么以及如何解决它。
interface.h文件:
#ifndef INTERFACE_H
#define INTERFACE_H
#include <iostream>
#include <string>
#include <fstream>
using namespace std; // I know this is a programming sin to include inside a header file but my textbook wants me to do it this way
class student
{
public:
student(); // class constructor
void setstudent(string studentName, string ID, string studentNumber, string diploma); // Function im using to set objects in array object
private:
string studentName;
string ID;
string studentNumber; // class variables
string diploma;
int averageMark;
string codes [5];
int marks [5];
};
#endif // INTERFACE_H
implementation.cpp文件:
#include <iostream>
#include "interface.h"
using namespace std;
student::student()
{
studentName = "";
ID = "";
studentNumber = ""; // constructor to initialise all class variables
diploma = "";
averageMark = 0;
codes [5] = {"", "", "", "", ""};
marks [5] = {0, 0, 0, 0, 0};
}
void student::setstudent(string studentName, string ID, string studentNumber, string diploma) // function to set class variables
{
cout << "Please enter a student name" << endl;
cin.getline(studentName);
cout << "Please enter a unique student ID" << endl;
cin.getline(ID);
cout << "Please enter a unique student number" << endl;
cin.getline(studentNumber);
cout << "Please enter diploma name" << endl;
cin.getline(diploma)
if (diploma == "Garden Design")
{
codes[5] = {"G1","G2","G3","G4","G5"};
}
else if (diploma == "Gourmet Cooking")
{
codes[5] = {"C1","C2","C3","C4","C5"};
}
}
main.cpp文件:
#include <iostream>
#include "interface.h"
using namespace std;
int main()
{
student studentDetails[3]; // Creation of class array object to store 3 objects / Maybe ive declared my array to hold 3 class objects incorrectly?
for (int i = 0; i < 3; i++)
{
studentDetails[i].setstudent(studentName, ID, studentNumber, diploma); // function call to set class variables for the objects
}
return 0;
}
如果有人能指出我做错了什么并指出我正确的方向将非常感激。
CodeBlocks错误:
||=== Build: Debug in student (compiler: GNU GCC Compiler) ===|
C:\Users\nicbe\Desktop\Student\student\main.cpp||In function 'int main()':|
C:\Users\nicbe\Desktop\Student\student\main.cpp|12|error: 'studentName' was not declared in this scope|
C:\Users\nicbe\Desktop\Student\student\main.cpp|12|error: 'ID' was not declared in this scope|
C:\Users\nicbe\Desktop\Student\student\main.cpp|12|error: 'studentNumber' was not declared in this scope|
C:\Users\nicbe\Desktop\Student\student\main.cpp|12|error: 'diploma' was not declared in this scope|
||=== Build failed: 4 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|
答案 0 :(得分:0)
错误正是它所说的:未被声明。
在您的主要功能中:
studentDetails[i].setstudent(studentName, ID, studentNumber, diploma);
突然,这四个论点凭空出现(?)。
不确定您是否刚刚排除了该部分或什么。