首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

帮忙找找异常吧

2012-03-16 
帮忙找找错误吧#include iostream.hstruct employee{int idfloat salary}void display(employee *p)

帮忙找找错误吧
#include "iostream.h"

struct employee
{
  int id;
  float salary;
};
void display(employee *p);

int main()
{
  int num;
  employee *emptr;
  cin >>num;
  emptr=new employee[num];
  cout <<"id:";
  cin >>emptr[3]->id;
  cout <<"salary:";
  cin >>emptr[3]->salary;
  display(emptr[3]);
  return 0;
}
void display(employee *p)
{
  cout <<"id:" <<p.id <<endl;
  cout <<"salary:" <<p.salary <<endl;
}


报错:type 'employee' does not have an overloaded member 'operator ->'

[解决办法]
#include "iostream.h"

struct employee
{
int id;
float salary;
};
void display(employee *p);

int main()
{
int num;
employee *emptr;
cin >>num;
emptr=new employee[num];
cout <<"id:";
cin >>emptr[3].id;
cout <<"salary:";
cin >>emptr[3].salary;
display(emptr[3]);
return 0;
}
void display(employee *p)
{
cout <<"id:" <<p.id <<endl;
cout <<"salary:" <<p.salary <<endl;
}

[解决办法]
同上
emptr[3]->id;不对
emptr是指针,要么(emptr+3)->id,要么emptr[3].id
[解决办法]
emptr[3]是一个employee类型,不是employee*类型,对employee类型,引用其成员就只能用.操作符了

C/C++ code
#include "iostream.h"struct employee{  int id;  float salary;};void display(employee *p);int main(){  int num;  employee *emptr;  cin >>num;// 如果num小于4,你下面使用3来索引就引起非法内存访问了  emptr=new employee[num];  cout <<"id:";  cin >>emptr[3].id;  cout <<"salary:";  cin >>emptr[3].salary;  display(emptr[3]);  return 0;}void display(employee *p){  cout <<"id:" <<[color=#0000FF]p->id[/color] <<endl;  cout <<"salary:" <<[color=#0000FF]p->salary[/color] <<endl;}
[解决办法]
typedef struct employee
{
int id;
float salary;
}*EMPLOYEE;
结构体可以这样定义指针试下
[解决办法]
我修改了一下,特别是头文件,你自己看吧。

#include <iostream>
using namespace std;

struct employee
{
int id;
float salary;
};
void display(employee *p);

int main()
{
int num;
employee *emptr;
cin >>num;
emptr = new employee[num];
cout <<"id:";
cin >>emptr[3].id;
cout <<"salary:";
cin >>emptr[3].salary;
display(&emptr[3]);
return 0;
}
void display(employee *p)
{
cout <<"id:" <<p->id <<endl;
cout <<"salary:" <<p->salary <<endl;
}

[解决办法]
emptr[3]是对象数组,
对象的指针才能用->取值

热点排行