#2
Geayou2022-07-17 17:57
|
下面的程序,我编写了一个复制构造函数,最后输出count的值时,结果是1
我不太理解
1、c1.returnPairCircle(c1)函数调用时,用c1去初始化函数中的形参时,应该调用1次复制构造函数
2、c2=c1.returnPairCircle(c1),函数返回值去复制给c2时,会再次调用一次复制构造函数
所以,我觉得count的值最后应该是2,而不是1,但是我又不知道问题出在哪里?
另外,下面的语句:
circle c2;
c2=c1.returnPairCircle(c1);
我改成下面的语句,编译器竟然报告错误:“error: cannot bind non-const lvalue reference of type 'circle&' to an rvalue of type 'circle'”,特别郁闷,不知道为什么?
circle c2=c1.returnPairCircle(c1);
#include <iostream>
#include <cmath>
using namespace std;
#include <cstring>
#define PI 3.14159
class circle{
friend ostream& operator<<(ostream &output,circle &ex){
output<<"x: "<<ex.x<<"\ny: "<<ex.y<<"\nr: "<<ex.r<<endl;
return output;
}
public:
circle(circle &);
circle(double=0,double=0,double=0);
void set(double,double,double);
double getRadio() const{return r;}
double returnArea() const{return r*r*PI;}
static int getcount(){return count;}
circle returnPairCircle(circle ex){
circle temp;
temp.x=-ex.x;
temp.y=-ex.y;
temp.r=ex.r;
return temp;
}
private:
double x;
double y;
double r;
static int count;
};
int circle::count=0;
circle::circle(circle &ex){
x=ex.x;
y=ex.y;
r=ex.r;
count+=1;
}
circle::circle(double x0,double y0,double r0)
:x(x0),y(y0),r(r0){
}
void circle::set(double x0,double y0,double r0){
x=x0;
y=y0;
r=r0;
}
int main() {
circle c1(2,2,5);
circle c2;
c2=c1.returnPairCircle(c1);
cout<<c2;
cout<<c2.getcount()<<endl;
return 0;
}