Bài tập

Viết chương trình C++ để nhận điểm và tính tổng điểm của sinh viên bởi sử dụng Lớp cơ sở ảo (Virtual Base Class) trong C++.

Lời giải

Dưới đây là chương trình C++ để giải bài tập trên. Sau đây là các bước mình liệt kê để bạn dễ theo dõi:

  • Bước 1: Khai báo lớp cơ sở sinhvien
  • Bước 2: Khai báo và định nghĩa hàm getnumber() và hàm putnumber()
  • Bước 3: Tạo lớp kế thừa diemthi được kế thừa ảo từ lớp cơ sở sinhvien
  • Bước 4: Khai báo và định nghĩa hàm getmark() và putmark()
  • Bước 5: Tạo lớp kế thừa gdthechat được kế thừa ảo từ lớp cơ sở sinhvien
  • Bước 6: Khai báo các hàm getscore() và putscore()
  • Bước 7: Tạo lớp kế thừa ketqua được kế thừa từ các lớp diemthi và gdthechat
  • Bước 8: Khai báo và định nghĩa hàm display() để tính toán tổng điểm
  • Bước 9: Tạo đối tượng obj của lớp kế thừa
  • Bước 10: Gọi các hàm getnumber(), getmark(), getscore(0 và display()


#include<iostream>
#include<conio.h>
using namespace std;

class sinhvien
{
   int mssv;
  public:
   void getnumber()
   {
              cout<<"Nhap MSSV: ";
              cin>>mssv;
   }
   void putnumber()
   {
              cout<<"\n\n\tMSSV la: "<<mssv<<"\n";
   }
};

class diemthi:virtual public sinhvien
{

  public:
   int diemthi1,diemthi2;
   void getmark()
   {
              cout<<"Nhap cac diem thi\n";
              cout<<"Diem thi 1 la: ";
              cin>>diemthi1;
              cout<<"Diem thi 2 la: ";
              cin>>diemthi2;
   }
   void putmark()
   {
              cout<<"\tCac diem thi da nhap\n";
              cout<<"\n\tDiem thi 1 la: "<<diemthi1;
              cout<<"\n\tDiem thi 2 la: "<<diemthi2;
   }
};

class gdthechat:public virtual sinhvien
{

  public:
    int diemtc;
    void getscore()
    {
              cout<<"Nhap diem Giao duc the chat: ";
              cin>>diemtc;
    }
    void putscore()
    {
              cout<<"\n\tDiem Giao duc the chat la: "<<diemtc;
    }
};

class ketqua:public diemthi,public gdthechat
{
    int tongdiem;
  public:
   void display()
   {
      tongdiem=diemthi1+diemthi2+diemtc;
      putnumber();
      putmark();
      putscore();
      cout<<"\n\tTong diem: "<<tongdiem;
   }
};

int main()
{
   ketqua obj;

   obj.getnumber();
   obj.getmark();
   obj.getscore();
   obj.display();
   return 0;
}

```Chạy chương trình C++ trên sẽ cho kết quả như hình sau:

![Bài tập về Lớp cơ sở ảo (Virtual Class) trong C++](../bai_tap_cplusplus_co_giai/images/su_dung_lop_co_so_ao_trong_cplusplus.PNG)" style="text-align: center"> <script async="" src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script><ins class="adsbygoogle" data-ad-client="ca-pub-2373417360267295" data-ad-slot="1837799362" style="display:inline-block;width:336px;height:280px"></ins><script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>

Viết câu trả lời

Drop Images

0 Bình luận