A Class with Dual Role

来源:互联网 发布:淘宝cpm是什么意思 编辑:程序博客网 时间:2024/06/16 19:53

Description

There is a class B and another class D. Their relationship is as following:
B is the base class of D and at the same time, D has a object member of the type of class B, as shown below. You should complete the definition of class D so that the main function can run successfully and its output as below.

#include <iostream>using namespace std;class B{private:int x;int y;public:B(int a , int b){x = a;y = b;}void print() const {cout<<x<<", "<<y<<endl;}};class D: public B{private:B member;  int c;public:// Your code will be included here.};int main(){int i, j, m, n, k;  cin>>i>>j>>m>>n>>k;  D(i, j, m, n, k).print();}

Input

6 3 4 5 8

Output

Printing from Base:6, 3Printing from member:4, 5Printing from D field:8

Hint

You need to define a constructor for D and redefine the print() function for D.
There is no '\n' at the end of output




My Answer:

#include "standard.hpp"#include <iostream>using namespace std;D::D(int a, int b, int c , int d , int e): B(a,b),member(c,d){   k = e;}void D::print(void) const{  cout<<"Printing from Base:"<<endl;  B::print();  cout <<"Printing from member:"<<endl;  member.print();  cout<<"Printing from D field:"<<endl;  cout <<k;}  


之前错误分析:

1.没有注意原题函数给出的形式,多加了cout
2.应使用初始化列表
3.两种方式调用print函数,一种是直接通过类的定义,另一种是通过类对象的成员函数。


原创粉丝点击