| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 986 人关注过本帖
标题:求教C++,关于复制构造函数,请各位大神帮忙答疑
只看楼主 加入收藏
tao12345678
Rank: 1
等 级:新手上路
帖 子:2
专家分:0
注 册:2022-5-30
收藏
 问题点数:0 回复次数:1 
求教C++,关于复制构造函数,请各位大神帮忙答疑
下面的程序,我编写了一个复制构造函数,最后输出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;
}
搜索更多相关主题的帖子: count double return 复制 构造函数 
2022-05-30 16:11
Geayou
Rank: 1
等 级:新手上路
帖 子:1
专家分:0
注 册:2022-7-17
收藏
得分:0 
复制构造函数只调用了一次
2022-07-17 17:57
快速回复:求教C++,关于复制构造函数,请各位大神帮忙答疑
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.016772 second(s), 9 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved