当类可能会创建临时对象时,拷贝构造函数的参数要加上const这个是标准的做法,不加的话在一些类调用拷贝构造函数创建临时对象的时候会报出错误,当然有些编译器不加也不会报错,像VC,但是最好的做法是加上const,又安全又符合标准,下面给出一个例子:
#include <iostream>
#include <cmath>
using namespace std;
class Point
{
private:
int x;
int y;
public:
Point(int xx=0, int yy=0){
x = xx;
y = yy;
cout<<"Calling the Costructor of Point."<<endl;
}
Point(Point const& p);
int getX(){ return x; }
int getY(){ return y; }
};
Point::Point(Point const& p){
x = p.x;
y = p.y;
cout<<"Calling the copy Costructor of Point."<<endl;
}
class Line
{
private:
Point p1,p2;
double length;
public:
Line(Point p1, Point p2);
Line(Line& l);
double getLength(){ return length; }
};
Line::Line(Point p1, Point p2):p1(p1),p2(p2){
double x;
double y;
x = p1.getX() - p2.getX();
y = p1.getY() - p2.getY();
length = sqrt( x*x + y*y );
cout<<"Calling constructor of Line."<<endl;
}
Line::Line(Line& l):p1(l.p1),p2(l.p2){
cout<<"Calling the copy Constructor of Line."<<endl;
length = l.length;
}
int main(void){
Point p1(3, 4);
Point p2(8, 10);
cout<<"length = "<<Line( Point(3,4) ,Point(5,6) ).getLength()<<endl;
//cout<<Point(4,6).getX()<<Line(p1, p2).getLength()<<endl;
return 0;
}
当Point的复制构造函数的参数没有加上const时,g++编译器会报错,但是windows下VC是不会报出错误的。但是最好还是把const加上,这样更加符合我们所要做的事情——仅仅是拷贝内容。