请看下面的代码: 我有类facultyType,并在main中创建了一个250对象的类数组。 在print方法中传递Faculty(facultyType数组),但在调用其程序时停止并且没有编译错误。 我想在print方法中迭代所有facultyType并想要访问其成员函数。在java做同样的工作正常,但我担心为什么它不在这里工作。
#include<iostream>
#include<string>
using namespace std;
class facultyType
{
private:
string firstname;
string lastname;
string department;
double salary;
int serviceyears;
public:
facultyType(){}
void print(facultyType* faculty,int count);
void setAll(facultyType faculty[],float percent,int count);
//setter and getter
};
void facultyType::print(facultyType* faculty,int count)//need help here
{
int i;
for(i=0;i<count;i++)
{
//want to iterate all facultyType one by one
facultyType f=faculty[i];//here the problem
int serviceYear;
serviceYear =f.getServiceYears();//not getting the exact values
cout<<"service year "<<serviceYear<<endl;
cout<<"dfhh"<<endl;
if(serviceYear>=15) {
cout<<f.getFirstName()<<"\n"<<f.getLastName()<<"\n"
<<f.getDepartment();
cout<<f.getSalary()<<"\n"<<f.getServiceYears()<<endl;
cout<<"-------------------------------------------------\n";
}
}
}
int main()
{
facultyType Faculty[250];
facultyType f;
int count=0;
int status=0;
string fname,lastname,depart;
double sal;
int serviceyears;
while(status!=4)
{
cout<<"1. Add new Faculty member"<<endl;
cout<<"2. increase all faculty member salary"<<endl;
cout<<"3. Print Employee"<<endl;
cout<<"4. Exit"<<endl;
cin>>status;
switch(status)
{
case 1:
{
cout<<"Enter first name : ";
cin>>fname;
//..other code for setter and getter values
Faculty[count]=newFaculty;
count++;
break;
}
case 3:{
f.print(Faculty,count);//calling print method
break;
}
case 4: break;
}
}
return 0;
}
我知道它最愚蠢的问题,但我是c ++的新手。 请解释为什么它与Java不同。 提前谢谢。
答案 0 :(得分:3)
问题是你的&#34; getter&#34;函数实际上没有返回任何东西。在您按照以下方式编辑facultyType::setServiceYears
之前:
int facultyType::getServiceYears()
{
serviceyears;
}
应该是(添加return
关键字):
int facultyType::getServiceYears()
{
return serviceyears;
}
这是一种在启用警告时被编译器捕获的错误。
我使用:g++ test.cpp -ggdb -O0 -Wall -Wextra -pedantic