4-1 C++对象指针
例子:
上图:new会自动调用构造函数,而c语言的malloc只是开辟内存;
4-2 C++对象指针实践
Coordinate.h
class Coordiante
{
public:
Coordiante();
~Coordiante();
public: //同样的访问限定符可以出现多次
int m_iX;
int m_iY;
};
Coordinate.cpp
#include "Coordinate.h"
#include <iostream>
using namespace std;
Coordiante::Coordiante()
{
cout<<"Coordiante()"<<endl;
}
Coordiante::~Coordiante()
{
cout<<"~Coordiante()"<<endl;
}
demo.cpp
#include<iostream>
#include<stdlib.h>
#include"Coordinate.h"
using namespace std;
int main(void)
{
Coordiante *p1 = NULL;
p1 = new Coordiante;//构造函数时默认构造函数的时候可以写括号也可以不写括号;
Coordiante *p2 = new Coordiante();
p1->m_iX = 10;
p1->m_iY = 20;
(*p2).m_iX = 30;//*p2是一个对象
(*p2).m_iY = 40;
cout<<p1->m_iX+(*p2).m_iX<<endl;
cout<<p1->m_iY+(*p2).m_iY<<endl;
delete p1;
p1 = NULL;
delete p2;
p2 = NULL;
Coordiante p3;
Coordiante *p4 = &p3;
p4->m_iX = 10;
(*p4).m_iY = 20;
cout<<p3.m_iX<<endl;
cout<<p3.m_iY<<endl;
system("pause");
return 0;
}
运行结果:
Coordiante()
Coordiante()
40
60
~Coordiante()
~Coordiante()
Coordiante()
10
20
请按任意键继续. . .
多行注释: 先CTRL+K,然后CTRL+C
取消注释: 先CTRL+K,然后CTRL+U