派生类 构造函数 初始化列表问题 求助!

liuyang3x 2012-07-20 11:37:49
include <iostream>

using namespace std;



class Point

{

public:

Point(float xx=0,float yy=0)

{

X=xx;

Y=yy;

}

void Move(float xOff,float yOff)

{

X+=xOff;

Y+=yOff;

}

float GetX()

{

return X;

}

float GetY()

{

return Y;

}

private:

float X;

float Y;

};

class Rectangle:public Point

{

public:

Rectangle(float x,float y,float w,float h):Point(x,y)

{



W=w;

H=h;

}

float GetH()

{

return H;

}

float GetW()

{

return W;

}

private:

float H,W;

};





int main()

{

Rectangle rect(2,3,20,10);

rect.Move(2,3);

cout<<rect.GetX()<<endl;

cout<<rect.GetY()<<endl;

cout<<rect.GetW()<<endl;

cout<<rect.GetH()<<endl;

system("pause");

return 0;

}




输出结果为 4,6,20,10

但是当把rectangle类的构造函数改为


Rectangle(float x,float y,float w,float h):

{

Point(x,y);

W=w;

H=h;

}


把Point类的构造函数放在函数体内,而不是初始化列表

结果就是2,3,20,10;

能不能解释一下是为什么

...全文
77 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
pathuang68 2012-07-20
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 的回复:]

兄弟,你是学java还是C#转行过来的?
还是你根本没认真看过C++教材?Point类的构造函数能放在函数体内么。
[/Quote]

C++中没有第二种写法。
yuqangy 2012-07-20
  • 打赏
  • 举报
回复
Point(x,y);//这个是临时对象,不是你父类的
taodm 2012-07-20
  • 打赏
  • 举报
回复
兄弟,你是学java还是C#转行过来的?
还是你根本没认真看过C++教材?Point类的构造函数能放在函数体内么。

64,645

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧