对象成员指针学习

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;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值