编程论坛's Archiver

sishui198 发表于 2008-5-15 15:13

为什么拷贝构造函数出现了四次

#include<math.h>
#include<iostream.h>
class point
{
private:
         int x,y;
public:
        point (int xx=0,int yy=0)
        {
                x=xx;
                y=yy;
        }
point (point &p);

        int getx()
        {
                return x;
        }
        int gety()
        {
                return y;
        }
};
point::point(point &p)
{
        x=p.x;
        y=p.y ;
        cout<<p.x;
        cout<<"point 拷贝构造函数被调用"<<endl;
}
class distance
{
private :
        point p1,p2;
        double dist;
public :
    distance(point xp1,point xp2);
        double getdis()
        {
                return dist;
        }
};
        distance::distance(point xp1,point xp2):p1(xp1),p2(xp2)
        {
                        cout<<"distance 拷贝构造函数被调用"<<endl;
                        double x=double(p1.getx()-p2.getx());
                        double y=double(p1.gety()-p2.gety());
                        dist =sqrt(x*x+y*y);
        }
void main()
{
        point myp1(1,1),myp2(4,5);
        distance myd(myp1,myp2);
        cout<<"the distance is:";
        cout<<myd.getdis()<<endl;

}
我跟踪发现这些拷贝构造函数都来自        distance::distance(point xp1,point xp2):p1(xp1),p2(xp2)
为什么?

[[it] 本帖最后由 sishui198 于 2008-5-15 16:03 编辑 [/it]]

p1s 发表于 2008-5-15 23:50

你改为
distance::distance(point &xp1,point &xp2):p1(xp1),p2(xp2)
看看还有几次。
估计是对象的值传递的时候造成了无名对象,但事实上还是要调用拷贝构造函数。
如果改了以后还剩2次说明就是这个问题。

vfdff 发表于 2008-5-17 20:14

拷贝构造函数出现了2次

我在 cfree 3.5 下运行
#include<math.h>
#include<iostream.h>

class point
{
private:
    int x,y;
public:
    point (int xx=0,int yy=0) {
        x=xx; y=yy;
    }
    point (point &p);

    int getx() { return x; }
    int gety() { return y; }
};
point::point(point &p)
{
    x=p.x; y=p.y ;
    cout<<p.x<<"point 拷贝构造函数被调用"<<endl;
}

class distance
{
private :
    point p1,p2;
    double dist;
public :
    distance(point xp1,point xp2);
    double getdis() {
        return dist;
    }
};
distance::distance(point p1,point p2)//:p1(xp1),p2(xp2)
{
    cout<<"distance 拷贝构造函数被调用"<<endl;
    double x=double(p1.getx()-p2.getx());
    double y=double(p1.gety()-p2.gety());
    dist = sqrt(x*x+y*y);
}
   
void main()
{
    point myp1(1,1),myp2(4,5);
    distance myd(myp1,myp2);
    cout<<"the distance is:";
    cout<<myd.getdis()<<endl;
}

[[it] 本帖最后由 vfdff 于 2008-5-17 20:30 编辑 [/it]]

sishui198 发表于 2008-5-18 14:26

你是把两个屏蔽了,如果按照我给的那个,确实是4次

sishui198 发表于 2008-5-18 14:33

谢谢了,我知道哦为什么了。

页: [1]

Powered by Discuz! Archiver 6.1.0  © 2001-2007 Comsenz Inc.