}
运行结果:
构造函数被调用: (6.8,98.23) //主函数第一行,定义对象c1,调用带两个参数的构造函数 缺省构造函数被调用: (0,0) //主函数第一行,定义对象c2,调用不带参数的构造函数 复制构造函数被调用: (6.8,98.23) //主函数第二行,调用函数fun(),实参c1初始化形参c,调
用复制构造函数
在函数 fun()中. //frn()函数的第一行
构造函数被调用: (68,198.23) //fun()函数第五行,定义对象temp,调用带两个参数的构
造函数
复制构造函数被调用: (68,198.23) //fun()函数结束,创建临时对象将返回值带到主函数中 析构函数被调用: (68,198.23) // fun()函数结束,析构对象temp 析构函数被调用: (6.8,98.23) // fun()函数结束,析构开参对象c 析构函数被调用: (68,198.23) //临时对象被析构
c2=(68,198.23) //主函数中的第三、第四行 析构函数被调用: (68,198.23) //主函数结束,析构对象c2 析构函数被调用: (6.8,98.23) //主函数结束,析构对象c1 Press any key to continue
2.定义一个score类,其中包括私有数据成员和公有成员函数,即 num 学号 Math 高等数学成绩 English 英语成绩 Programming 程序设计成绩 Inscore() 计算平均成绩并输出 showscore() 输出学号和各科成绩
score( ) 构造函数有两个,分别带有参数和不带参数两种。
使用score类,输入某班5个学生的学号和各科成绩,然后求各个学生的平均成绩,并输出学生的学号、各科成绩和平均成绩。利用对象数组实现。 程序代码:
#include
public: Score(); Score(int,double,double,double); double In_Score(); //计算平均成绩函数 void Show_Score(); //输出学生信息函数 private: int num; double Math,English,Programming; };
Score::Score() { cout<<\请输入学生的学号、数学、英语、C++的成绩:\ cin>>num; cin>>Math>>English>>Programming; }
Score::Score(int n,double m,double e,double p) { num=n; Math=m; English=e; Programming=p; }
void Score::Show_Score() { cout<<\ cout<<\ cout<<\ cout<<\ cout<<\ cout<<\}
double Score::In_Score() { return (Math+English+Programming)/3; }
int main() { Score stu[5]; int i; for(i=0;i<5;i++) stu[i].Show_Score(); return 0; }
运行结果:
请输入学生的学号、数学、英语、C++的成绩: 10 70 70 70
请输入学生的学号、数学、英语、C++的成绩: 11 80 80 90
请输入学生的学号、数学、英语、C++的成绩: 12 69 79 89
请输入学生的学号、数学、英语、C++的成绩: 13 70 82 84
请输入学生的学号、数学、英语、C++的成绩:
14 60 69 79
********Student Info******** num=10 math=70 english=70 cprogram=70 average=70
********Student Info******** num=11 math=80 english=80 cprogram=90 average=83.3333
********Student Info******** num=12 math=69 english=79 cprogram=89 average=79
********Student Info******** num=13 math=70 english=82 cprogram=84 average=78.6667
********Student Info******** num=14 math=60 english=69 cprogram=79 average=69.3333
Press any key to continue
3. 编写程序完成堆栈类的定义,实现相应基本操作。 程序代码:
#include %using namespace std; #define MaxSize 10 class Stack_int {
private: int top; int data[MaxSize]; public: Stack_int();
~Stack_int(); void display(); void push(int); void pop(int &); int empty(); int read_top(); };
Stack_int::Stack_int() { top=-1; cout<<\调用构造函数!\}
Stack_int::~Stack_int() { cout<<\调用析构函数!\}
void Stack_int::display() { if(top==-1) cout<<\空栈,没有元素!\ else { cout<<\栈中元素:\ for(int i=top;i>=0;i--) cout< void Stack_int::push(int x) { if(top>=MaxSize-1) cout<<\栈已满,无法进行进栈操作!\ else { top++; data[top]=x; } } void Stack_int::pop(int &x) { if(top==-1) cout<<\空栈,无法进行出栈操作!\ else { x=data[top]; top--; } } int Stack_int::empty() { if(top==-1) return 1; else return 0; } int Stack_int::read_top() { if(top==-1) { cout<<\空栈,没有元素,返回特定值0!\ return 0; } else { return data[top]; } } int main() { Stack_int s1; int m,x; while(1) { cout<<\进栈操作 2:出栈操作\ cout<<\判栈空操作 4:读取栈顶元素\ cout<<\显示栈元素 6:退出\ cout<<\请输入选择:\ cin>>m; switch(m) { case 1: { cout<<\输入进栈元素\ cin>>x; s1.push(x); break; } case 2: