c++ new与this是什么意思

来源:学生作业帮助网 编辑:作业帮 时间:2024/05/09 06:48:58
c++ new与this是什么意思

c++ new与this是什么意思
c++ new与this是什么意思

c++ new与this是什么意思
new 用于动态分配内存,在内存堆区分配.
如:
char *p = new char[1024];
用new分配后一定要记得最后 delete []p;
this 是类内部的一个隐藏的指针.它的数据类型是本类类型.
如:
class Car
{
public:
Car();
Car();
void setColor(char *color);
char *getColor(void) const;
private:
char *aColor;
double aWidth;
double aHeight;
}
...
void Car::setColor(char *color) // 实质是void Car::setColor(Car *this,char *color)
{
aColor = new char[strlen(color) + 1]; // 实质是this.aColor = new char[strlen(color) + 1]
strcpy(aColor,color); // 实质是strcpy(this.aColor,color)
}
delete []aColor; // Car 中放这个
被static 与 const 限制过的成员函数 实质就是限制了那个隐藏的this指针.
这里不说了,想深入了解我们可以交流交流.
只是在类中用到它的时候没有显示的声明,其实每个类都有一个这样的指针.
也不是很神秘,跟普通的类指针没有两样.

都关键字
new 的功能主要是动态分配内存,然后将首指针返回。比如
#include
int main()
{
int * p=new int[10];
for(int i=0;i<10;i++)p[i]=i+10;
for(int i=0;i<10;i++)std::cout<

全部展开

都关键字
new 的功能主要是动态分配内存,然后将首指针返回。比如
#include
int main()
{
int * p=new int[10];
for(int i=0;i<10;i++)p[i]=i+10;
for(int i=0;i<10;i++)std::cout<}
而this是类的内部特殊指针,指向类的本身。比如
#include
class CMan
{
public:
CMan(int age,int tel){this->m_age=age;this->m_tel=tel;
void Print()
{
std::cout<<"age:"<m_age<<" tel:"<tel<}
private:
int m_age;
int m_tel;
};
int main()
{
CMan one(30,123456);
one.Print();
}

收起