标签:显示 point 函数 oid namespace 理解 通过 类变量 log
class point
{
private:
int xPos;
int yPos; public:
point();
};
point::point()
{
xPos = 0;
yPos = 0;
}
//point.h
#include <iostream>
using namespace std;
class point //point类定义,在定义同时实现其成员函数
{
private: //私有成员,分别代表x轴和y轴坐标
int xPos;
int yPos;
public:
point(int x, int y) //有参构造函数
{
cout << "对象创建时构造函数被自动调用" << endl;
xPos = x; yPos = y;
}
void print() //输出信息
{
cout << "xPos: " << xPos << ",yPos: " << yPos << endl;
}
};
#include "point.h"
int main()
{
// point pt0;//错误的调用,因为我们已经显示的定义了一个带参数的构造函数
// pt0.print();//输出pt0的信息
point pt1(3, 4); //调用有参构造函数声明point类变量(类对象)pt1 pt1.print(); //输出pt1的信息
return 0;
}
例1:
#include <iostream>
using namespace std;
class Point
{
public:
Point()//构造函数能够进行重载
{
cout << "Point()" << endl;
}
Point(int ix, int iy)
{
cout << "Point(int,int)" << endl;
_ix = ix;
_iy = iy;
}
void print()
{
cout << "(" << _ix<< "," << _iy<< ")" << endl;
}
private:
int _ix;
int _iy;
};
int main(void)
{
Point p1;//调用默认构造函数
p1.print();
Point p2(3, 4);
p2.print();
return 0;
}
//point1.h
#include <iostream>
using namespace std;
class point //point类定义,在定义同时实现其成员函数
{
public:
point(int x, int y)//有参构造函数
{
cout << "有参构造函数的调用" << endl;
xPos = x;
yPos = y;
}
point() //无参构造函数
{
cout << "无参构造函数的调用" << endl;
xPos = 0;
yPos = 0;
}
void print()//输出信息
{
cout << "xPos: " << xPos << ",yPos: " << yPos << endl;
}
private: //私有成员,分泌诶代表x轴和y轴坐标
int xPos;
int yPos;
};
#include "point1.h"
int main()
{
point pt1(3, 4); //调用有参构造函数声明point类变量(类对象)pt1 pt1.print(); //输出pt1的信息
point pt2; //调用无参构造函数声明point类变量(类对象)pt2 pt2.print(); //输出pt2的信息
return 0;
}
point(int x=0,int y=0)
{
cout<<"对象创建时构造函数被自动调用"<<endl;
xPos=x;
yPos=y;
}
point pt; //x和y都采用默认值0
point pt(3); //x为3,y采用默认值0
point pt(3,4);//x为3,y为4,两个参数都不采用默认值
point(int x,int y)
{
cout<<"有参构造函数的调用"<<endl;
xPos=x;
yPos=y;
}
//等价于:
point(int x,int y)
:xPos(x)
,yPos(y)
{
cout<<"有参构造函数的调用"<<endl;
}
//point.h
#include <iostream>
using namespace std;
class point
{
private:
int yPos; //先定义
int xPos; //后定义
public:
point(int x)
:xPos(x)
, yPos(xPos) //初始化表取决于成员声明的顺序
//如果换成
//:yPos(y)
//,x(yPos)//这样的话,x先初始化,但是这时yPos还没有初始化,x就是不确定的值了
{
}
void print()
{
cout << "xPos: " << xPos << ", yPos: " << yPos << endl;
}
};
#include "point.h"
int main()
{
point pt1(3); //调用有参构造函数声明变量pt1
pt1.print();
return 0;
}
#include <iostream>
using namespace std;
class Point
{
public:
#if 0
Point()//构造函数能够进行重载
{
cout << "Point()" << endl;
}
#endif
Point(int ix, int iy)
: _ix(ix)//初始化列表
, _iy(iy)
{
cout << "Point(int,int)" << endl;
//_ix = ix;//赋值
//_iy = iy;
}
void print()
{
cout << "(" << _ix
<< "," << _iy
<< ")" << endl;
}
private:
int _ix;
int _iy;
};
int main(void)
{
Point p1;//调用默认构造函数
p1.print();
Point p3(5);
p3.print();
Point p2(3, 4);
p2.print();
return 0;
}
标签:显示 point 函数 oid namespace 理解 通过 类变量 log
原文地址:http://www.cnblogs.com/Burgess-Fan/p/7049988.html