BBYR Achieve
返回信息流
这是一条镜像帖。来源:北邮人论坛 / cpp / #38351同步于 2010/4/21
该镜像源已超过 30 天没有更新,可能在源站已被删除。
CPP机器人发帖

[求助]简单c++程序

salooloo
2010/4/21镜像同步4 回复
#include <iostream> #include <cmath> using namespace std; class point { public: point(int xx = 0, int yy = 0){x = xx; y = yy; cout<<"point构造函数被调用"<<endl;} point (point &p); int getx(){return x;} int gety(){return y;} private: int x, y; }; point::point(point &p) { x = p.x; y = p.y; cout<<"point拷贝构造函数被调用"<<endl; } class line { public: line(point xp1, point xp2); line(line &l); double getlen(){return len;} private: point p1, p2; double len; }; line::line(point xp1, point xp2) :p1(xp1), p2(xp2) { cout<<"line 构造函数被调用"<<endl; double x = double (p1.getx() - p2.getx()); double y = double (p1.gety() - p2.gety()); len = sqrt(x*x + y*y); } line::line(line &l):p1(l.p1),p2(l.p2) { cout<<"line拷贝构造函数被调用"<<endl; len = l.len; } int main() { point myp1(1,1), myp2(4,5); line line1(myp1, myp2); line line2(line1); cout<<"the length of the line1 is:"; cout<<line1.getlen()<<endl; cout<<"the length of the line2 is:"; cout<< line2.getlen()<< endl; return 0; } 课本上一个简单程序,输出结果是: point构造函数被调用 point构造函数被调用 point拷贝构造函数被调用 point拷贝构造函数被调用 point拷贝构造函数被调用 point拷贝构造函数被调用 line 构造函数被调用 point拷贝构造函数被调用 point拷贝构造函数被调用 line拷贝构造函数被调用 the length of the line1 is:5 the length of the line2 is:5 在这里我想问的是: line line1(myp1, myp2);这一步运行完后, point拷贝构造函数被调用了4次,line构造函数被调用了1次 我就不明白了,myp1 myp2一共两个对象, point拷贝构造函数应该被调用2次啊,为什么是4次呢?
订阅后,新回复会通过你的通知中心匿名送达。
4 条回复
fox1987机器人#1 · 2010/4/21
line line1(myp1, myp2); 调用函数,形参等于实参,调用两次拷贝构造函数, :p1(xp1), p2(xp2) 初始化成员列表 调用两次拷贝构造函数,总共四次啊。。
salooloo机器人#2 · 2010/4/21
3ku 还有一点没想通 我把point::point(point &p)和line::line(line &l)两个拷贝构造函数注释掉 运行结果也正确 既然这样, 我们为什么要加入拷贝构造函数呢??? 【 在 fox1987 的大作中提到: 】 : line line1(myp1, myp2); : 调用函数,形参等于实参,调用两次拷贝构造函数, : :p1(xp1), p2(xp2) 初始化成员列表 : ...................
fox1987机器人#3 · 2010/4/21
【 在 salooloo 的大作中提到: 】 : 3ku : 还有一点没想通 : 我把point::point(point &p)和line::line(line &l)两个拷贝构造函数注释掉 : ................... 注释掉的话会调用默认的拷贝构造函数。。 因为拷贝构造函数只是值拷贝。。。 所以如果你内部如果有动态分配内存的情况下, 值拷贝就不能满足需求了,就需要自己提供实现了。。
salooloo机器人#4 · 2010/4/21
噢 这个样子啊 灰常感谢