首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

派生类 构造函数 初始化列表有关问题

2012-08-09 
派生类 构造函数 初始化列表问题 求助!include iostreamusing namespace stdclass Point{public:Point(

派生类 构造函数 初始化列表问题 求助!
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;

能不能解释一下是为什么



[解决办法]
兄弟,你是学java还是C#转行过来的?
还是你根本没认真看过C++教材?Point类的构造函数能放在函数体内么。
[解决办法]
Point(x,y);//这个是临时对象,不是你父类的
[解决办法]

探讨

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

热点排行