C++对象成员实践(坐标类,线段类)

1.题目如下所示:

 

 2.来吧,展示:

#头文件Line.h文件

#include "Coordinate.h"

class Line
{
public:
    Line(int x1,int y1,int x2,int y2);
    ~Line();
    void setA(int x,int y);
    void setB(int x,int y);
    void printInfo();
private:
    Coordinate m_coorA;
    Coordinate m_coorB;
};

#头文件Coordinate.h文件

#include "Coordinate.h"
class Coordinate
{
public:
    Coordinate(int x,int y);
    ~Coordinate();
    void setX(int x);
    int getX();
    void setY(int y);
    int getY();
private:
    int m_iX;
    int m_iY;
};

#源函数Line.cpp

#include <iostream>
#include "Line.h"
using namespace std;

Line::Line(int x1,int y1,int x2,int y2):m_coorA(x1,y1),m_coorB(x2,y2)
{
    cout << "Line()" << endl;
}

Line::~Line()
{
    cout << "~Line()" << endl;
}

void Line::setA(int x,int y)
{
    m_coorA.setX(x);
    m_coorA.setY(y);
}

void Line::setB(int x,int y)
{
    m_coorB.setX(x);
    m_coorB.setY(y);
}

void Line::printInfo()
{
    cout << "(" << m_coorA.getX() << "," << m_coorA.getY() << ")" << endl;
    cout << "(" << m_coorB.getX() << "," << m_coorB.getY() << ")" << endl;
}

#源函数Coordinate.cpp

#include <iostream>
#include "Coordinate.h"
using namespace std;

Coordinate::Coordinate(int x,int y)
{
    m_iX = x;
    m_iY = y;
    cout << "Coordinate()" << m_iX << "," << m_iY << endl;
}

Coordinate::~Coordinate()
{
    cout << "~Coordinate()" << m_iX << "," << m_iY << endl;
}

void Coordinate::setX(int x)
{
    m_iX = x;
}
int Coordinate::getX()
{
    return m_iX;
}

void Coordinate::setY(int y)
{
    m_iY = y;
}
int Coordinate::getY()
{
    return m_iY;
}

#主函数demo.cpp文件

#include <iostream>
#include <stdlib.h>
#include "Line.h"
using namespace std;

int main(void)
{
    Line *p = new Line(1,2,3,4);
    p->printInfo();
    delete p;
    p = NULL;
    system("pause");
    return 0;
}

3.运行结果:

 

 4.这里小关需要解释一下运行结果的含义,

实例化的时候是先实例化了坐标A,再实例化坐标B,再实例化线段,

销毁的时候是先销毁线段,再销毁坐标B,再销毁坐标A

 

希望能帮到大家,问你们要一个赞,你们会给吗,谢谢大家
版权声明:本文版权归作者(@攻城狮小关)和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
大家写文都不容易,请尊重劳动成果~
交流加Q:1909561302
CSDN地址https://blog.csdn.net/Mumaren6/

 

posted @ 2020-09-28 10:31  攻城狮小关  阅读(388)  评论(0编辑  收藏  举报