Constructor
#给Python程序员的注释: C++中的构造函数类似于Python中的 __init__ 方法.
#include <iostream>
using namespace std;
class Point
{
public:
Point(int x = 0, int y = 0) //带有默认参数的构造函数
{
cout<<"自定义的构造函数被调用...\n";
xPos = x; //利用传入的参数值对成员属性进行初始化
yPos = y;
}
void printPoint()
{
cout<<"xPos = " << xPos <<endl;
cout<<"yPos = " << yPos <<endl;
}
private:
int xPos;
int yPos;
};
int main()
{
Point M(10, 20); //创建对象M并初始化xPos,yPos为10和20
M.printPoint();
Point N(200); //创建对象N并初始化xPos为200, yPos使用参数y的默认值0
N.printPoint();
Point P; //创建对象P使用构造函数的默认参数
P.printPoint();
return 0;
}Last updated