1. 程式人生 > >初學程式設計C++

初學程式設計C++

物件成員編碼示例:

#include<iostream>
#include<stdlib.h>
#include"Coordinate.h"
#include"Line.h"
using namespace std;
/*
  物件成員:
     要求:
	      定義兩個類:
		  座標類:Coordinate
		  資料成員:橫座標m_iX;縱座標m_iY;
		  成員函式:建構函式、解構函式、資料封裝函式
		  線段類:Line
		  資料成員:點A m_coorA,點B m_coorB
		  成員函式:建構函式、解構函式、資料封裝函式、資訊列印函式
		  */
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;
};
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;
}
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;
};
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<<"coorA"<<"("<<m_coorA.getX()<<","<<m_coorA.getY()<<")"<<endl;
	cout<<"coorB"<<"("<<m_coorB.getX()<<","<<m_coorB.getY()<<")"<<endl;
}

int main(void){
	Line*p=new Line(1,2,3,4);
	delete p;

	system("pause");
	return 0;
}

列印結果 在這裡插入圖片描述