C++创建对象时什么时候用*,什么时候不用*
用*, 表示创建的是一个指针对象,C++中用new关键字开辟内存。
另外指针对象访问成员变量用-> , 非指针用. 就这么个原则
但是指针也可以不用-> 例如 (*p).age 所以->其实就是先*后.的简写吧
同样一个问题:
C++用new和不用new创建类对象区别?
使用new, 必须配套使用delete,调用delete时才会调用析构函数,若不delete,那么可能造成内存泄漏, delete时还要注意,delete NULL会崩溃
不用new, 析构函数会自动执行
代码:
#include <iostream> #include <string.h> using namespace std; class Person{ public: ~Person(){ cout << "Person析构函数" << endl; } public: string *name; int age; }; int main(int argc, const char * argv[]) { // insert code here... std::cout << "Hello, World!\n"; // Person *p1 = new Person(); // cout << p1->age << endl; // delete p1; Person p2 = Person(); cout << p2.age << endl; return 0; }
下面是一个简单的动态数组的代码:
#ifndef MyArray_hpp #define MyArray_hpp #include <stdio.h> class MyArray { public: MyArray(); MyArray(int capacity); MyArray(const MyArray& array); ~MyArray(); //尾插法 void push_Back(int val); //根据索引获取值 int getData(int index); //根据索引设置值 void setData(int index,int val); private: int *pAdress; int m_Size; int m_Capacity; }; #endif /* MyArray_hpp */
#include "MyArray.hpp" #include <iostream> using namespace std; MyArray::MyArray() { this->m_Capacity = 100; this->m_Size = 0; this->pAdress = new int[this->m_Capacity]; } MyArray::MyArray(int capacity){ this->m_Capacity = capacity; this->m_Size = 0; this->pAdress = new int[this->m_Capacity]; } MyArray::MyArray(const MyArray& array){ this->pAdress = new int[array.m_Capacity]; this->m_Size = array.m_Size; this->m_Capacity = array.m_Capacity; } MyArray::~MyArray(){ cout << "析构函数调用" << endl; if (this->pAdress != NULL) { delete [] this->pAdress; this->pAdress = NULL; } } void MyArray::push_Back(int val){ this->pAdress[this->m_Size] = val; this->m_Size++; } int MyArray::getData(int index){ return this->pAdress[index]; } void MyArray::setData(int index, int val){ this->pAdress[index] = val; }
void test01(){ MyArray *array1 = new MyArray(30); //(MyArray *) array1 = 0x0000000100648440 MyArray array2; /* { pAdress = 0x0000000100649240 m_Size = 0 m_Capacity = 100 } */ MyArray array = MyArray(30); /* { pAdress = 0x000000010064b680 m_Size = 0 m_Capacity = 30 } */ }
这位老师说的很细 https://blog.csdn.net/qq_35644234/article/details/52702673
此文仅为鄙人学习笔记之用,朋友你来了,如有不明白或者建议又或者想给我指点一二,请私信我。liuw_flexi@163.com/QQ群:582039935.
我的gitHub: (学习代码都在gitHub)
https://github.com/nwgdegitHub/