建構函式中呼叫建構函式new和delete使用小結
阿新 • • 發佈:2019-01-02
malloc free 是C語言的函式
new delete 是C++的操作符
#include "iostream"
using namespace std;
//構造中呼叫構造是危險的行為 因為會生成匿名物件 匿名物件會消失
class MyTest
{
public:
MyTest(int a, int b, int c)
{
this->a = a;
this->b = b;
this->c = c;
}
MyTest(int a, int b)
{
this ->a = a;
this->b = b;
MyTest(a, b, 100); //直接呼叫建構函式 產生新的匿名物件 沒有物件去接 那麼匿名物件將會被析構
//匿名物件和 呼叫匿名物件的物件 t1 沒有半毛錢關係
}
~MyTest()
{
printf("MyTest~:%d, %d, %d\n", a, b, c);
}
protected:
private:
int a;
int b;
int c;
public:
int getC() const { return c; }
void setC(int val) { c = val; }
};
int main()
{
MyTest t1(1, 2);
printf("c:%d", t1.getC()); //請問c的值是?
//因為匿名物件的生命週期 暫時的
//呼叫建構函式 產生的是匿名物件 並且產生的匿名物件與呼叫的物件沒有半毛錢的關係 而且會被很快的釋放掉
system("pause");
return 0;
}
#include <iostream>
using namespace std;
// C /C++ malloc free
// new delete 操作符 C++的語法
// 基礎型別變數 分配陣列變數 分配物件
//
int main()
{
int * p = (int *)malloc(sizeof(int));
*p = 10;
free(p);
int *p2 = new int; //C++分配基礎型別
*p2 = 20;
delete p2;
// 使用new 並且對申請的記憶體進行初始化
int *p3 = new int(30);
cout << "* p3 = " <<*p3 << endl;
delete p3;
cout << "hello world!" << endl;
system("pause");
return 0;
}
new和delete的新增的功能
#include <iostream>
using namespace std;
// C /C++ malloc free
// new delete 操作符 C++的語法
// 基礎型別變數 分配陣列變數 分配物件
//
int main06()
{
//分配陣列 C語言中
int *p = (int *) malloc(sizeof(int )*10);
p[0] = 10;
cout << p[0] << endl;
free(p);
int *pArray = new int[10];
pArray[0] = 22;
cout << "pArray[0] = " << pArray[0] << endl;
delete [] pArray; //刪除陣列的正確方法 要加上 []
cout << "hello world!" << endl;
system("pause");
return 0;
}
class Tea
{
public:
Tea(int _a)
{
a = _a;
cout << "這是一個建構函式" << endl;
}
~Tea()
{
cout <<"這是一個解構函式" << endl;
}
protected:
private:
int a;
};
void playboy()
{
Tea *pT1 = (Tea *)malloc(sizeof(Tea));
if(pT1 != NULL)
{
free(pT1);
}
Tea *pT2 = new Tea(10); ///呼叫建構函式
delete pT2; //delete會呼叫解構函式
}
//分配物件
//////////////////////////////////////////////////////////////////////////
//new 可以執行 建構函式
//delete 函式可以執行函式的解構函式
//////////////////////////////////////////////////////////////////////////
int main()
{
playboy();
cout << "hello world!" << endl;
system("pause");
return 0;
}
malloc free 和 new delete 在使用基礎資料的時候是可以混搭
在使用類的物件的時候 malloc不會呼叫建構函式
free 不會呼叫解構函式