#include<iostream> using namespace std; class Student { public: Student(int n,float s):num(n),score(s){} void change(int n,float s){num=n;score=s;} void display(){cout<<num<<" "<<score<<endl;} private: int num; float score; }; int main() { Student stud(101,78.5); stud.display(); stud.change(101,80.5); stud.display(); return 0; } 修改上述程序,增加一个fun 函数,改写main 函数。改为在fun函数中调用 change 和display 函数。在fun 函数中使用对象的引用(Student &)作形参。
时间: 2024-01-15 09:04:31 浏览: 33
修改后的程序如下:
```
#include<iostream>
using namespace std;
class Student {
public:
Student(int n, float s) : num(n), score(s) {}
void change(int n, float s) { num = n; score = s; }
void display() { cout << num << " " << score << endl; }
private:
int num;
float score;
};
void fun(Student &stud) {
stud.display();
stud.change(101, 80.5);
stud.display();
}
int main() {
Student stud(101, 78.5);
fun(stud);
return 0;
}
```
在新的程序中,我们增加了一个函数 `fun`,它的形参是 `Student &` 类型的引用,即对象的引用。在 `fun` 函数中,我们首先调用 `display` 函数输出当前对象的信息,然后调用 `change` 函数修改对象的信息,最后再次调用 `display` 函数输出修改后的信息。在 `main` 函数中,我们创建了一个 `Student` 类型的对象 `stud`,并将它作为实参传递给 `fun` 函数。运行程序后,输出结果和原来的程序一样。
相关问题
#include<iostream> #include<string> using namespace std; namespace student2 { class Student { public: Student(int n,string nam,char s,float sco) { num=n; name=nam; sex=s; score=sco; } void show_data(); private: int num; string name; char sex; float score; }; void Student::show_data() { cout<<"num:"<<num<<" name:"<<name<<" sex:"<<sex<<" score:"<<score<<endl; } }
这是一个C++程序,包含了头文件iostream和string,并定义了一个命名空间student2和一个类Student。该类包含了一个构造函数和一个成员函数show_data,构造函数用于初始化类的数据成员,show_data函数用于输出数据成员的值。
该类的数据成员包括num、name、sex和score,分别表示学号、姓名、性别和成绩。show_data函数用于输出这些数据成员的值。
该程序中使用了命名空间student2,可以避免命名冲突。如果在程序中使用了多个类或函数,并且它们的名称相同,可以使用命名空间来区分它们。
在C++中#include <iostream> using namespace std; class Student {public: Student(int n,float s):num(n),score(s){} int num; float score; }; int main() {Student stud[5]={ Student(101,78.5),Student(102,85.5),Student(103,98.5), Student(104,100.0),Student(105,95.5)};这段代码中的主函数表达啥意思
有哪些数据类型?
C中有基本数据类型和派生数据类型两种类型。基本数据类型包括int、float、double、char等,用于表示基本数据类型的值。派生数据类型包括数组、结构体、联合体和指针等,用于表示不同类型数据的集合或者指向数据的指针。在C中同时支持有符号和无符号的数据类型。