[ C++ ] Kế thừa trong C++ [Lập trình hướng đối tượng với C++]

Kế thừa trong C++ (Inheritance)


Kế thừa là một đặc trưng quan trọng trong lập trình hướng đối tượng (OOP). Sự kế thừa trong các ngôn ngữ lập trình như C++, Java, C#, VB.Net,.. cơ bản là giống nhau.

Trong lập trình C++, có thêm khái niệm đa kế thừa mà các ngôn ngữ khác đã bỏ chức năng này do sự nhập nhằng khi sử dụng.

Khái niệm: Kế thừa là cách tạo lớp mới từ các lớp đã được định nghĩa từ trước [Wiki]


Trong đó:
    - Class A: lớp cơ sở (lớp cha) - supper class
    - Class B: lớp dẫn xuất (lớp con) - sub class

Class B có thể dùng được hầu hết các phương thức (hàm thành viên) và các thuộc tính (biến thành viên) của lớp A ngoại trừ các các phương thức và các hàm các tính chất private.

Cài đặt: để cài đặt lớp kế thừa ta dùng toán tử ":".  Ví dụ B kế thừa A viết là:  B:A
   [Code]
     class A{
        ....
      };

     class B:A{
         ...
     };

Lưu ý:
   - Một lớp cha có thể có nhiều lớp con (có phép kế thừa)
   - Đến lượt mình mỗi lớp con lại có thể có các con khác
   - Trong C++ cho phép đa kế thừa (một lớp con có thể nhận hơn 1 lớp cha)

Xet ví dụ: Xây dựng lớp cha (Nguoi), lớp con (HocSinh)

 [Code Tubor C++]
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
#include<string.h>

// lop cha
class Nguoi
{
protected:
char hoTen[30];
int namSinh;
private:
char soThich[50]; // so thich
public:
Nguoi(){ // khoi tao lop Nguoi
 strcpy(hoTen,"Nguyen Van A");
 namSinh=1990;
 strcpy(soThich,"Lap trinh");
}
 void InTT(); // In thông tin
};
// lop con
class HocSinh : public Nguoi
{
protected:
 int maHS;
public:
 void Nhap();
 void InTT();
};
// InTT cua cha (Nguoi)
void Nguoi::InTT()
{
cout << "\n Nam sinh : " << namSinh;
cout << "\n Ho ten : " << hoTen;
cout << "\n So thich : " << soThich;
}
// InTT cua con (HocSinh)
void HocSinh::InTT()
{
cout << "\n Ma hoc sinh : " << maHS;
cout << "\n Nam sinh : " << namSinh;
cout << "\n Ho ten : " << hoTen;
}
//  Nhap thong tin
void HocSinh::Nhap()
{
cout << "\n Nam sinh : "; cin>> namSinh;
cout << "\n Ho ten : "; gets(hoTen);
cout << "\n Ma hoc sinh: "; cin>> maHS;
}

// ham main ---------------------------------------------
void main(){

    // khai bao doi tuong Nguoi
    Nguoi a;  a.InTT();
   // khai bao doi tuong HocSinh
        HocSinh t;   t.Nhap();  t.InTT();

   getch();
}

//Giải thích: Do lớp HocSinh kế thừa lớp cha Nguoi => lớp HocSinh chứa các thuộc tính: hoTen, namSinh, maHS; các phương thức: InTT(); Nhap(); lớp HocSinh không thể kế thừa được thuộc tính soThich do tích chất của nó là private.

[ Android ] Xây dựng ứng dụng nhập vào số nguyên n; tính giai thừa của n, in kết quả.


Vi dụ: Xây dựng ứng dụng nhập vào số nguyên n; tính n!; in kết quả.

>> Thực hiện: 

- Create Android Project: TinhGiaiThua




- Thiết lập và code:

+ Res\layout\main.xml:


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

    
       

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/n" />

        <EditText
            android:id="@+id/txtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="0.12" 
            android:hint="Input"
            android:inputType="text|textAutoCorrect|textCapWords|number"
            />

           <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="0.12"
            android:text="Tinh" />
        
    <TextView
        android:id="@+id/kq"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/kq" />
    
    

</LinearLayout>

+ Res\value\string.xml



<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="hello">Nhap so can tinh</string>
    <string name="app_name">Tính giai thừa</string>
    <string name="kq">Kết quả:</string><string name="n">N:</string>
    

</resources>

+ rsc\...

package txt.Begin.TinhGiaiThua;


import android.app.Activity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.TextView;
public class TinhGiaiThuaActivity extends Activity {     // Phuong thuc tinh giai thua public int GiaiThua(int a){ int gt=1; for(int i=1;i<=a;i++) gt=gt*i; return gt; } // onCreate     public void onCreate(Bundle savedInstanceState) {            super.onCreate(savedInstanceState);        setContentView(R.layout.main);               final Button tinh=(Button) findViewById(R.id.button1);        final TextView ketqua=(TextView) findViewById(R.id.kq);                     // xu ly nut button        tinh.setOnClickListener(new Button.OnClickListener(){        public void onClick(View v) {        String so=((EditText) findViewById(R.id.txtn)).getText().toString();        int n=Integer.parseInt(so);        try
{        int s=GiaiThua(n);        ketqua.setText("");        ketqua.setText(ketqua.getText()+""+(s));         } catch (Exception ex)
{
ketqua.setText(ex.toString());
}        }                });                   }}


>> Kết quả:




*******

Một số tài liệu và khoá học bổ ích dành cho bạn: 

# Giáo trình: Lập Trình Android [Click để xem]

# Khoá học online:  Lập trình Android toàn tập [Click để xem]

-----------------------------------------

[ Android ] Ứng dụng Giải phương trình bậc 2

Vi dụ: Xây dựng ứng dụng giải phương trình: ax^2+bx+c=0 (trong đó a, b, c được nhập vào qua EditText)


>> Thực hiện: 

- Create Android Project: GiaiPhuonTrinhBac2



- Thiết lập và code:

+ Res\layout\main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Giai PT bac 2"
/>
<TextView
    android:text="He so a:"
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content">  
</TextView>
<EditText
    android:id="@+id/a"
    android:numeric="integer"
    android:layout_width="200sp"
    android:layout_height="wrap_content"
  android:hint="@string/edit_hint"  
    android:inputType="text|textAutoCorrect|textCapWords|number"
    android:textSize="18sp"
 
    />
<TextView
    android:text="He so b:"
    android:id="@+id/textView2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">  
</TextView>
<EditText
    android:id="@+id/b"
    android:numeric="integer"
    android:layout_width="200sp"
    android:layout_height="wrap_content"
    android:hint="@string/edit_hint"
    android:inputType="text|textAutoCorrect|textCapWords|number"
    android:textSize="18sp"
    />
<TextView
    android:text="He so c:"
    android:id="@+id/textView3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
 
</TextView>
<EditText
    android:id="@+id/c"
    android:numeric="integer"
    android:layout_width="200sp"
    android:layout_height="wrap_content"
  android:hint="@string/edit_hint"  
    android:inputType="text|textAutoCorrect|textCapWords|number"
    android:textSize="18sp"
 
    />
<Button
    android:id="@+id/calculate"
    android:text="Giai"
    android:layout_width="wrap_content"
    android:layout_height="83dp"/>
 
<TextView
    android:id="@+id/result"
    android:layout_height="200sp"
    android:layout_weight="0.25"
    android:layout_width="match_parent"/>
</LinearLayout>

+ Res\value\string.xml


<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Mời bạn nhập hệ số</string>
    <string name="app_name">Giai phuong trinh bac 2</string>
<string name="edit_hint">Input</string>
</resources>

+ rsc\...

package txt.Begin.GiaiPhuongTrinhBac2;
import android.app.Activity;
import android.os.Bundle;
import android.widget.*;
import android.view.*;
public class GiaiPhuongTrinhBac2Activity extends Activity {
  public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Button button = (Button) findViewById(R.id.calculate);
final TextView result = (TextView) findViewById(R.id.result);
button.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
String sa = ((EditText) findViewById(R.id.a)).getText().toString();
String sb = ((EditText) findViewById(R.id.b)).getText().toString();
String sc = ((EditText) findViewById(R.id.c)).getText().toString();
try
{
double a = Double.parseDouble(sa);
double b = Double.parseDouble(sb);
double c = Double.parseDouble(sc);
if (a == 0)
{
result.setText("Phuong trinh bac I: ");
if (b == 0)
{
if (c == 0)
result.setText(result.getText() + "PT co' vo so nghiem");
else
result.setText(result.getText() + "PT vo nghiem");
}
else
{
result.setText(result.getText() + "x=" + (-c/b));
}
}
else
{
double delta = b*b - (4*a*c);
if (delta < 0.0)
{
result.setText("PT vo nghiem \n");
}
else
if (delta == 0)
{
result.setText("PT co nghiem kep: " + (-b/(2*a)));
}
else
{
double delta_sqrt = Math.sqrt(delta);
result.setText("x1 = " + ((b*b + delta_sqrt)/(2 * a)) +"\n" + "x2 = " + ((b*b - delta_sqrt)/(2 * a)));
}
}
} catch (Exception ex)
{
result.setText(ex.toString());
}
}
    });
}
}
>> Kết quả:


[Xem thêm]

*******

Một số tài liệu và khoá học bổ ích dành cho bạn: 

# Giáo trình: Lập Trình Android [Click để xem]

# Khoá học online:  Lập trình Android toàn tập [Click để xem]

-----------------------------------------

[ Android ] Xây dựng ứng dụng: Nhập vào tên bạn, sau đó in ra lời chào bạn [Bắt đầu làm việc với Android]

Trước tiên hãy đảm bảo rằng Eclipse của bạn đã được Plug-In thư viện Android thành công [xem cách plug-in android tại đây].

Một ứng dụng Android cơ bản gồm các thành phần sau:



Trong đó, chúng ta phải thiết lập và code các file sau (bạn có thể copy và patse vào đúng vị trí):

1- Res \ layout (main.xml): 


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
 
    <EditText android:id="@+id/edit_text"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="@string/edit_hint" />
     
        <TextView android:id="@+id/text_view"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:textColor="@color/text_color"
            android:textSize="28px"
            android:typeface="monospace" />
</LinearLayout>


2- Res \ values:

 + string.xml (thiết lập các chuỗi ký tự):


<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, Example!</string>
    <string name="app_name">Loi chao: </string>
    <string name="edit_hint">Nhap vao ten cua ban!</string>
 </resources>


 + color.xml (thiết lập màu chữ):


<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="text_color">#ff3300</color>
</resources>


3- src \ [Package của bạn] \ [class chính của bạn] (chứa code xử lý) :


package txt.B.Nhap;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.EditText;
import android.widget.TextView;
public class NhapSOActivity extends Activity {
/** Called when the activity is first created. */

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Thiet lap giao dien lay tu file main.xml
setContentView(R.layout.main);
//Lay ve cac thanh phan trong main.xml thong qua id
final EditText edit = (EditText)
findViewById(R.id.edit_text);
final TextView text = (TextView)
findViewById(R.id.text_view);
//Xu ly cho su kien an nut giua tren dien thoai
edit.setOnKeyListener(
new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
String chao="Chao ban "+edit.getText().toString();
text.setText(chao);
edit.setText("");
return true;
}
else {
return false;
}
}
});
}
}

*** Chú ý: Bạn cần để ý tên Project mà bạn tạo để thay đổi code cho chuẩn.

>> Kết quả khi thực thi ứng dụng:





[Các bài viết liên quan]

*******

Một số tài liệu và khoá học bổ ích dành cho bạn: 

# Giáo trình: Lập Trình Android [Click để xem]

# Khoá học online:  Lập trình Android toàn tập [Click để xem]

-----------------------------------------


[ Pascal ] Ví dụ về cấu trúc điều khiển và mảng 1 chiều


{
Vi du 1: 
  In ra man hinh tat ca so nguyen duong gom 4 chu so, sao cho tong cac chu so >=10.
}

uses crt;
var a,dv,ch,tr,ng:integer; {dv: don vi, ch: chuc, tr: tram, ng: nghin}

Begin
 clrscr;

 writeln(' * IN DAY SO: ');

 for a:=1000 to 9999 do
  begin
   dv:=a mod 10;
   ch:=(a div 10) mod 10;
   tr:=(a div 100) mod 10;
   ng:=a div 1000;

   if (dv+ch+tr+ng >=10) then
    write(a,'; ');
  end;

 readln;
End.

{----------------------------------------------------------------}


{
Vi du 2: 
  Nhap vao day so nguyen gom n so (1<n<100). Dem so nguyen to co trong day so vua nhap
}

uses crt;
var
 a:array[1..100] of integer;
 n,d,i,j,kt : integer; {d: chua ket qua dem, kt: kiem tra}


Begin
 clrscr;

 {Nhap n}

 writeln(' * Nhap so phan tu: ');
 repeat
  begin
   write(' n= '); readln(n);
   if ((n<=1) or (n >=100)) then
     writeln(' Nhap lai n!');
  end
 until ((n>1) and (n<100));

 {Nhap day so}

 for i:=1 to n do
  begin
   write(' a[',i,']= ');
   readln(a[i]);
  end;

 {In day vua nhap}

 writeln(' Day vua nhap: ');
 for i:=1 to n do
  write(a[i],'; ');

 {Dem so nguyen to}

 d:=0;

 for i:=0 to n do
  begin
   {kiem tra xem a[i] co phai so nguye to khong}
    if (a[i]>0 ) then  
     begin
      kt:=0;
      for j:=2 to a[i]-1 do
        if (a[i] mod j=0) then
          kt:=1;
      if (kt=0) then
        d:=d+1;
      end;
 
  end;

 writeln(' => Co ',d,' so nguyen to trong day');

 readln;

End.



[ C# - ADO.Net ] Giới thiệu tóm tắt các đối tượng để kết nối dữ liệu (ADO.Net) trong C#


I. Đối tượng Sqlconnection  [using System.Data.SqlClient ;]

1. Kết nối theo đặc quyền hệ điều hành

Cú pháp 1 : 
Server = servername [ \InstanceName ];
Database = databasename;
Integrated Security = SSPI;

Cú pháp 2 :
Server = servername[ \InstanceName ];
Database = databasename;
Integrated Security = true;

Cú pháp 3 :
Server = servername [ \InstanceName ];
Initial Catolog = databasename;
Integrated Security = true;

       Chú ý :  Tài khoản đăng nhập phải được khai báo trong phần Login

2. Kết nối theo đặc quyền SQL Server

Cú pháp 1: 
Server = Servername[ \InstanceName ];
Database = Databasename;
Use ID = Username;
Password = YourPasword;
[Connection Timeout = second;]
[port = portno;]
[Persist Security Info = true;]

      Chú ý : Servername có thể là : (local) hoặc ( . ) hoặc (Địa chỉ IP) .

Cú pháp 2 : Với dạng Attachment và phiên bản SQL Server 2005 (SQLEXPRESS)

@”Data Source = (local)\SQLEXPRESS; AttachDbFilename = <Đường dẫn tới file Database>; Integrated Security = true; Use Instance = true”;

3. Tập tin lưu chuỗi kết nối
Ta có thể sử dụng các định dạng *.ini hoặc *.txt để lưu chuỗi kết nối hoặc lưu chuỗi kết nối ngay trong class hay form. Tuy nhiên khi làm việc với .Net chúng ta nên sử dụng định dạng *.config đã được hố trợ sẵn.

Cú pháp 1:
?xml version="1.0" encoding="utf-8" ?>
<configuration>  <connectionStrings>    <add name="SqlServer"         connectionString=          " Server = servername[ \InstanceName ]; Database = databasename; Integrated Security = true; "          providerName ="System.Data.SqlClient"/>  </connectionStrings></configuration>

 - Cách đọc nội dung chuỗi kết nối theo cú pháp 1 ta sử dụng phương thức connectionStrings của lớp connectionStringSettings thuộc không gian tên System.Configuration;

   *
*     *

II. Đối tượng SQLCommand

1. Khai báo
SqlCommand  sqlCommand;

2. Khởi tạo
Có 4 kiểm khởi tạo để khai báo khởi tạo đối tượng này
  + sqlCommand = new SqlCommand();
  + sqlCommand = new SqlCommand(string CommandText);
  + sqlCommand = new SqlCommand(string CommandText, SqlConnection   sqlConnection);
  + sqlCommand = new SqlCommand(string CommandText, SqlConnection   sqlConnection, SqlTrasaction sqlTransaction);

3. Các thuộc tính
  + CommandText: Cho phép khai báo một chuỗi phát biểu SQL Server
  
VD : 
 String strSQL = “Select * from TBLSinhvien”; sqlCommand = new SqlCommand(); sqlCommand.CommandText = strSQL;

  + CommandType
Cho phép ta chọn một trong 3  giá trị enum là : Text,TableDirect,StoredProcedure
VD:
String strSQL = “spDanhsachSV”; sqlCommand = new SqlCommand(); sqlCommand.CommandText = strSQL;am sqlCommand.CommandType = CommandType.StoredProcedure;

Lưu ý: khi thủ tục có tham số truyền vào thì ta có thể sử dụng đối tượng SqlParameterCollection hay SqlParameter

+ CommandTimeout
Cho phép khai báo thời gian chờ thực thi phát biểu SQL được tính bằng    giây 

VD : 
 String strSQL = “spDanhsachSV”; sqlCommand = new SqlCommand(); sqlCommand.CommandText = strSQL; sqlCommand.CommandType = CommandType.StoredProcedure; sqlCommand.CommandTimeout = 30;

 + Connection
Cho phép ta khởi tạo đối tượng sqlConnection mà không cần phải thông  qua Constructor 

 VD : 
 String strSQL = “spDanhsachSV”; sqlCommand = new SqlCommand(); sqlCommand.CommandText = strSQL; sqlCommand.Connection = sqlConnection; sqlCommand.CommandType = CommandType.StoredProcedure; sqlCommand.CommandTimeout = 30;

4. Phương thức

+ Phương thức ExecuteNonQuery
   Thực thi các phát biểu SQL, thử tục nội tại, và nó trả về số bản ghi đựoc thực thi

VD :
sqlCommand.Connection = sqlConnection; sqlConnnection.Open();  String strSQL = “delete from TBLSinhvien where Masv = ‘SV0000001’”;  sqlCommand = new SqlCommand();  sqlCommand.CommandText = strSQL;  int records = sqlCommand.ExcuteNonQuery(); sqlConnection.Close(); sqlConnection.Dispose();

+ Phương thức ExecuteScalar
      Phương thức này thực thi phát biểu SQL Server giá trị trả về là kiểu đối tượng (object)
Nó thường được dùng để lấy giá trị của tổng các mấu tin hay giá trị của cột hay hàng thứ nhất

+ Phương thức ExecuteReader
      Khác với hai phương thức trên , phương thức này trả về tập các giá trị chỉ đọc một chiều và dùng đối tượng  sqlDataReader để nắm dữ tập dữ liệu đó.

 +  Phương thức ExcuteXmlReader
      Phương thức này tương tự như phương thức ExecuteReader nhưng nó trả về tập dữ liệu có định dạng XML và sử dụng đối tượng XMLReader để nắm dữ tập dữ liệu đó.

5. Xây dựng lớp dùng chung cho SQLServer
      Khi chúng ta muốn sử dụng các phương thức trên chung trong cơ sở dữ liệu SQL Server ,để có thể truyền vào tham số thì chúng ta sẽ xây dụng lớp dùng chung , giả sử là Database và kêt hợp với đôí tượng SqlConnection ở phần trên .

--------------------------------------------------------------------
Clip ví dụ về kết nối cơ sở dữ liệu với C# [đầy đủ - dễ hiểu]


[Nguôn: Kenhsinhvien]

Tìm kiếm nội dung khác: