1. 程式人生 > >C++基礎:

C++基礎:

什麼是多型:(啞巴了吧,你知道你倒是說呀),所謂多型也就是一個介面的多種實現方式。

多型包括:虛擬函式,純虛擬函式,覆蓋,模板(過載與多型沒有關係)

虛擬函式:虛擬函式是帶有virtual關鍵字的函式,定義一個函式為虛擬函式,定義他為虛擬函式是為了允許用基類的指標來呼叫子類的這個函式。純虛擬函式是 類似 virtual void hanShu(int B)=0;這樣的函式。帶有純虛擬函式的類是抽象類,必須例項化純虛擬函式後才能進行物件的生成。C++的虛擬函式主要作用是“執行時多型”

建構函式解構函式在繼承類時候的呼叫關係是:

先基類構造然後派生類構造,先派生類析構再基類析構。你繼承你爹的財產不得禮讓一點兒,先滿足他老人家的需求再滿足自己的需求啊,有什麼事兒的時候不得自己先擔著然後讓你爹站你後面啊!

  1. char*p="hello"
  2. const char*q="hello"
  3. int a[]="tsinghua"
  4. const int b[]="tsinghua"

p是等於q的,因為指標是個型別,好比 int 型別;a!=b,因為a 和b其實是兩段記憶體的初始地址

#pragma once
#include "stdafx.h"
#include <iostream>
using namespace  std;
class A
{
public:
    virtual void print()
    {
        cout << " this is A" << endl;
    }
};
class B:public A
{
    
public:
    virtual void print()
    {
        cout << "this is B" << endl;
    }
};
class MyString
{
    //預設是private型別 struct 預設是public型別;
    public:
    char* str;
public:
    MyString(const char* str1=NULL)
    {
        if (str1 == NULL)
            str = NULL;
        else
        {
            str = new char[strlen(str1)+1];
            strcpy_s(str,strlen(str1)+1, str1);
        }
    }
    ~MyString();
    MyString operator=(const MyString& mstr);
    
};
MyString::~MyString()
{
    delete[]this->str;
}
MyString MyString::operator=(const MyString&mystr)
{
    //面得把自己賦值給自己出錯
    if (this != &mystr)
    {
        delete[]this->str;
        this->str = NULL;
        if (mystr.str != NULL)
        {
            this->str = new char[strlen(mystr.str)];
            strcpy_s(str, strlen(mystr.str), mystr.str);
        }
    }
    return *this;
}
int main()
{
    A* ptr_a = new A();
    ptr_a->print();
    A* ptr_b = new B();
    ptr_b->print();
    MyString ms=MyString("hello my_string");
    cout << ms.str << endl;
    getchar();
    return 0;
}

這個輸出鐵定的是A函式的倆輸出,但是加上virtual 關鍵字第二個就變成B的函式輸出了。