首页 > 代码库 > C++ 构造器 普通构造器 代理构造器

C++ 构造器 普通构造器 代理构造器

第一种:

常见构造器:


Point.h

#ifndef POINT_H_
#define POINT_H_


class Point {
private:
int x = 1;
int y = 1;
public:
Point(); //该构造器实现在Point.cpp
Point(int x, int y);
int get_x(){return this->x;}
int get_y(){return this->y;}
virtual ~Point();
};


#endif /* POINT_H_ */


Point.cpp

#include "Point.h"


Point::Point() {
// TODO Auto-generated constructor stub
}


Point::Point(int x , int y) {
// TODO Auto-generated constructor stub
this->x = x;
this->y = y;
}


Point::~Point() {
// TODO Auto-generated destructor stub
}


Test.cpp

#include"Point.h"
#include<iostream>


using namespace std;
/*
 * Test.cpp
 *
 *  Created on: 2014年5月21日
 *      Author: John
 */




int main(int argc, char* argv[]){


Point pt;
Point pt1(2,2);


cout<<pt.get_x()<<" , " <<pt.get_y()<<endl;
cout<<pt1.get_x()<<" , " <<pt1.get_y()<<endl;


return 0;
}

输出 

1 , 1
2 , 2


第二种:代理构造器

 Point.h

#ifndef POINT_H_
#define POINT_H_


class Point {
private:
int x ;
int y ;
public:
//Point(); //该构造器实现在Point.cpp
Point(int x, int y);
Point():Point(0,0){}  //内嵌 不用分号结尾
//这行代码声明了一个默认构造器,但它把工作转交给另一个构造器:
//它调用了那个有两个输入参数的构造器,并把输入参数值(0,0)传递给了后者
//无论是使用在类声明里对乘员进行初始化,还是使用代理构造器
//均需要找个地方声明默认构造器
//前者使用Point();后者使用Point():Point(0,0){}
int get_x(){return this->x;}
int get_y(){return this->y;}
virtual ~Point();
};


#endif /* POINT_H_ */

Point.cpp

Point::Point(int x , int y) {
// TODO Auto-generated constructor stub
this->x = x;
this->y = y;
}

Point::~Point() {
// TODO Auto-generated destructor stub
}


Test.cpp不变

输出

0 , 0
2 , 2