關於C++中建立匿名類的時的情況
阿新 • • 發佈:2018-12-26
當類可能會建立臨時物件時,拷貝建構函式的引數要加上const這個是標準的做法,不加的話在一些類呼叫拷貝建構函式建立臨時物件的時候會報出錯誤,當然有些編譯器不加也不會報錯,像VC,但是最好的做法是加上const,又安全又符合標準,下面給出一個例子:
當Point的複製建構函式的引數沒有加上const時,g++編譯器會報錯,但是windows下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; }