coordinate.h
#ifndef COORDINATE_H
#define COORDINATE_H
class coordinate
{
public:
coordinate(int x, int y);
~coordinate();
int getX();
int getY();
private:
int m_iX;
int m_iY;
};
#endif // COORDINATE_H
coordinate.app
#include "coordinate.h"
#include <iostream>
using namespace std;
coordinate::coordinate(int x, int y)
{
m_iX = x;
m_iY = y;
cout << "::coordinate(int x, int y)" ;
cout << "(" << m_iX <<"," << m_iY << ")"<< endl;
}
coordinate::~coordinate()
{
cout << "~coordinate()" << "("
<< m_iX <<"," << m_iY << ")"<< endl;
}
int coordinate::getX()
{
return m_iX;
}
int coordinate::getY()
{
return m_iY;
}
line.h
#ifndef LINE_H
#define LINE_H
#include "coordinate.h"
class line
{
public:
line(int x1, int y1, int x2, int y2);
~line();
void printfInfo();
private:
coordinate *coo1;
coordinate *coo2;
};
#endif // LINE_H
line.app
#include "line.h"
#include <iostream>
using namespace std;
line::line(int x1, int y1, int x2, int y2)
{
/***重要
coordinate *coo1 = new coordinate(x1, y1);
coordinate *coo2 = new coordinate(x2, y2);
这里用coordinate *coo1
coordinate *coo2
犯了一个错误,相当于重新实例化两个对象,
虽然在终端内能正常调用构造函数,
但是析构函数却没有执行,
我猜测应该是.h文件中定义的连个对象没有用到,
没有去用构造函数,多以当然也不能再去析构
正确应该如下,直接实例化,不要再去定义了:
*/
但是析构函数
coo1 = new coordinate(x1, y1);
coo2 = new coordinate(x2, y2);
cout << "line()" << endl;
}
line::~line()
{
delete coo1;
coo1 = NULL;
delete coo2;
coo2 = NULL;
cout << "~line()" << endl;
}
void line::printfInfo()
{
cout << "printfInfo()" << endl;
cout << "(" << coo1->getX() << "," << coo1->getY()
<< ")" <<endl;
cout << "(" << coo2->getX() << "," << coo2->getY()
<< ")" <<endl;
}
main.app
#include <iostream>
#include "line.h"
using namespace std;
int main(int argc, char *argv[])
{
line *p = new line(1, 2, 3, 4);
p->printfInfo();
delete p;
p = NULL;
cout << sizeof(p) << endl; //8 64GCC bit
cout << sizeof(line) << endl;//16 64gcc bit
return 0;
}