c++,new,delete,成員指針

new和delete用來申請動態內存空間,必定要配對使用ios

#include <string>    
#include <ctype.h>
#include <vector>
#include <iostream>  
#include <fstream>


// using declarations states our intent to use these names from the namespace std    
using namespace  std;

int main()
{
    int *p = static_cast<int*>(malloc(sizeof(int))); 
    //對於內置類型,如int,double,float,char...即便不用new聲明,使用delete釋放也不會出任何編譯,運行錯誤,可是對於任何類類型,無論是自定義仍是系統自帶的,都會出錯誤
//隊伍malloc分配後用delete釋放,我進內存看過,能夠正常的釋放掉內存中的數據,徹底可行
int s = 1;
int *s = &s;
delete s; //飄紅的這三行能夠編譯經過,運行也沒問題,可是,調試的時候會出錯,千萬不要這樣作!!! int *p_new = new int; //分配一個int類型的地址空間,不進行初始化 int *p_new_1 = new int(10);//初始化爲10 int n = 10;//若是n過大,會致使內存申請失敗拋出錯誤,若是不想拋出錯誤能夠再new後面加上nothrow
//爲何說是動態分配內存,由於n是變量,是不肯定的,因此每次分配的內存不肯定,是在運行時分配
char *p_new_array = new(nothrow) char[n];//對於內置類型,n爲0時這樣寫沒問題,並且能夠進行解引用,而且直接delete不用數組括號也行 string *p_new_string = new string[n];//n爲0時沒法進行解引用,會報錯,不加括號的delete出錯,也不能進行解引用。 cout << *p << endl; cout << *p_new << endl; cout << *p_new_1 << endl; cout << *p_new_array << *(p_new_array+1) << endl; //delete p;// 基本內置類型能夠,對於類類型這樣不行,由於不是用new聲明的 delete p_new;p_new=null;//將懸空指針變爲空指針 delete p_new_1; p_new_1=null; delete p_new_array; p_new_array=null;//錯誤的寫法,只對基本內置類型有效 delete[]p_new_string; //正確的寫法,要和相應的new配對 return 0; }

 

成員地址,是相對於開始地址的相對偏移。c++

#include <string>    
#include <ctype.h>
#include <vector>
#include <iostream>  
#include <fstream>
#include<new>


// using declarations states our intent to use these names from the namespace std    
using namespace  std;
struct Date
{
    int year;
    int month;
    int day;
    void print(){ cout << year << "-" << month << "-" << day << endl; }
};

void showYear(Date a[], int length, int Date::*year);
int main()
{
    Date a[5] = { { 2001, 1, 1 }, { 2002, 2, 2 }, { 2003, 3, 3 }, { 2004, 4, 4 }, { 2005, 5, 5 } };
    Date d = { 1997, 7, 9 };
    cout << "&d = " << &d << endl;
    cout << "&d.year = " << &d.year << " &d.month = " << &d.month << " &d.day =" << &d.day << endl; //絕對地址
    cout << &Date::year << &Date::month << &Date::day << endl;//成員地址打印出來是111,c++認爲成員地址和函數地址無心義,因此都直接處理爲true,在輸出也就顯示爲1
    //cout << static_cast<int*>(&Date::year) << endl; //那麼,強轉來看看地址,結果報錯,不能轉換
    //匿名聯合,兩個變量同用同一個空間
    union 
    {
        int n;
        int Date::*mp;
    };
    mp = &Date::day;
    cout << "n = " << n << endl;//輸出8,相對於year的地址
    //經過成員地址來訪問結構中的成員
    cout << d.*mp << endl;

    //應用,訪問a數組中的,全部日期中的年份
    showYear(a, sizeof(a)/sizeof(Date), &Date::year);

    //成員函數指針
    d.print();
    void (Date::*p)() = &Date::print;
    (d.*p)();
    return 0;
}

void showYear(Date a[], int length, int Date::*p)//p是date中某個成員的地址,不可用day,year,month,會形成表達模糊
{
    for (int i = 0; i < length;++i)
    {
        cout << a[i].*p << " "; //a[i].year表達不出我想要用成員地址的意願,由於year原本就是成員
        //p是成員地址,*p是結構中的某個成員,a[i].*p,取出這個成員
    }
    cout << endl;
}
相關文章
相關標籤/搜索