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


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

#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; }

 

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

#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;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM