关于C++中创建匿名类的时的情况

        当类可能会创建临时对象时,拷贝构造函数的参数要加上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加上,这样更加符合我们所要做的事情——仅仅是拷贝内容。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值