#include<iostream> using namespace std; class Student{ public: Student(char n='li',int nu=1,int s=80):name(n),number(nu),score(s){} private: char name; int number; int score;}; int main() {Student a[5]= {Student('li',1,80), Student('hu',2,81), Student('chen',3,84), Student('pi',4,80), Student('ji',5,50) }; Student *p; p=a; cout<<*(p+1)<<endl; }这个程序哪里错了
时间: 2024-03-23 10:43:53 浏览: 58
这个程序有两个问题:
1. 在类中,name 应该是一个字符串类型,而不是一个字符类型。应该将其改为 `string name;`。
2. 在 `cout<<*(p+1)<<endl;` 中,你试图输出一个 Student 对象的值,但是没有为 Student 类型定义输出运算符。你需要为 Student 类型定义一个输出运算符,例如:
```
ostream& operator<<(ostream& os, const Student& s){
os << s.name << " " << s.number << " " << s.score;
return os;
}
```
然后才可以使用 `cout<<*(p+1)<<endl;` 来输出 Student 对象的值。
相关问题
指出下面程序中的错误,说明错误的原因,并进行改正 #include <iostream>using namespace std;class Student {public: char name[10]; int age; float aver; void printStu();};int main() { Student p1,p2,p3; p1.age = 30; return 0;}
该程序存在两个错误,包括:
1. `#include <iostream>using namespace std;` 应改为 `#include <iostream> using namespace std;`
2. `Student p1,p2,p3;` 中的逗号应该为英文逗号,否则编译器将无法正确识别变量声明。应改为 `Student p1, p2, p3;`
改正后的代码如下:
```
#include <iostream>
using namespace std;
class Student {
public:
char name[10];
int age;
float aver;
void printStu();
};
int main() {
Student p1, p2, p3;
p1.age = 30;
return 0;
}
```
定义一个描述学生基本情况的类,数据成员包括:年龄、姓名、性别;成员函数包括:输入和输出各个数据成员的值。 分别给出如下的3个文件: ①含类定义的头文件student.h, //student.h class Student { public: void display( ); private: int num; char name[20]; char sex; }; ②包含成员函数定义的源文件student.cpp //student.cpp #include <iostream> using namespace std; #include "student.h" void Student::display( ) { cout<<"num: "<<num<<endl; cout<<"name: "<<name<<endl; cout<<"sex: "<<sex<<endl; } ③包含主函数的源文件main.cpp。 为了组成一个完整的源程序,应当有包括主函数的源文件: //main.cpp #include <iostream> using namespace std; #include "student.h" int main( ) {Student stud; stud.display(); return 0; } 请完善该程序,在类中增加一个对数据成员赋初值的成员函数set_value。修改补充代码并上机运行
/student.h
```c++
class Student {
public:
void display();
void set_value(int n, char *nam, char s);
private:
int num;
char name[20];
char sex;
};
```
/student.cpp
```c++
#include <iostream>
#include "student.h"
using namespace std;
void Student::display() {
cout << "num: " << num << endl;
cout << "name: " << name << endl;
cout << "sex: " << sex << endl;
}
void Student::set_value(int n, char *nam, char s) {
num = n;
strcpy(name, nam);
sex = s;
}
```
/main.cpp
```c++
#include <iostream>
#include "student.h"
using namespace std;
int main() {
Student stud;
stud.set_value(1001, "Tom", 'M');
stud.display();
return 0;
}
```
阅读全文
相关推荐













