期末考试 编程题#2:输出指定结果一(Coursera 程序设计与算法 专项课程3 C++程序设计 郭炜、刘家瑛;OpenJudge)

来源:互联网 发布:国外数据库 编辑:程序博客网 时间:2024/05/17 04:55

编程题#2:输出指定结果一

来源: 北京大学在线程序评测系统POJ (Coursera声明:在POJ上完成的习题将不会计入Coursera的最后成绩。)

总时间限制: 1000ms 内存限制: 1024kB

描述
填写代码,使输出结果为
2
2
8
10

#include <iostream>using namespace std;class Number {public:    int num;    Number(int n): num(n) {    }// 在此处补充你的代码};int main() {    Number a(2);    Number b = a;    cout << a.value() << endl;    cout << b.value() << endl;    a.value() = 8;    cout << a.value() << endl;    a+b;    cout << a.value() << endl;    return 0;}

输入
不需要输入。

输出
使输出结果为
2
2
8
10

样例输入

不需要输入。

样例输出

22810

程序解答:

#include <iostream>using namespace std;class Number {public:    int num;    Number(int n) : num(n) {    }    // 在此处补充你的代码    //Number(Number& a) : num(a.num){}  //复制构造函数。如果定义的自己的复制构造函数,则默认的复制构造函数不存在    int& value(){ return num; }       //返回引用类型    void operator+(Number& b){        //重载 +        num += b.num;    }};int main() {    Number a(2);    Number b = a;  //使用默认的复制构造函数    cout << a.value() << endl;    cout << b.value() << endl;    a.value() = 8;    cout << a.value() << endl;    a + b;    cout << a.value() << endl;    return 0;}
阅读全文
0 0
原创粉丝点击