在构造函数中设置变量的默认值

时间:2013-11-19 05:46:29

标签: c++

我编写了这段代码并且在传递一个三参数构造函数时遇到了麻烦,它将第一个设置为房间号,第二个是房间容量,这里是我被困的三个部分是设置房价,将房间占用率设置为0 这里是我写的代码

#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <string>


using namespace std;

class HotelRoom
{
private:
string room_no;
int Capacity;
int occupancy;
double rate;
public:
HotelRoom();
HotelRoom(string, int, int, double );

};  
HotelRoom::HotelRoom (string room, int cap, int occup = 0, double rt )
{
room_no = room;
Capacity = cap;
occupancy = occup;
rate = rt;

cout << " Room number is " << room_no << endl;
cout << " Room Capacity is " << Capacity << endl;
cout << " Room rate is " << rate << endl;
cout << "Occupancy is " << occup << endl;
}

int _tmain(int argc, _TCHAR* argv[])

{

cout << setprecision(2)
     << setiosflags(ios::fixed)
     << setiosflags(ios::showpoint);

HotelRoom Guest (" 123", 4, 55.13);


system("pause");
return 0;
}

3 个答案:

答案 0 :(得分:4)

HotelRoom::HotelRoom (string room, int cap, int occup = 0, double rt )

是非法的,如果您提供默认值,则必须

  • 之后没有参数
  • 以下所有参数也必须具有默认值

要解决此问题,请将占用作为构成函数中的最后一个变量。

HotelRoom::HotelRoom (string room, int cap, double rt, int occup=0 )

另一个注意事项:

只提供标题中的默认值,重写默认值会在声明过程中出错。

header.h

HotelRoom(string,int,double,int occup=0);

imp.cpp

HotelRoom::HotelRoom (string room, int cap, double rt, int occup ) 
{
    //...
}

答案 1 :(得分:2)

除了Gmercer015的答案。在C ++ 11中,您可以使用delegating constructors

HotelRoom::HotelRoom (string room, int cap, int occup, double rt )
{
    ...
}

HotelRoom::HotelRoom (string room, int cap, double rt )
    : HotelRoom(room, cap, 0, rt)
{}

答案 2 :(得分:1)

AFAIR,没有参数,默认值不能跟参数。在你的情况下你应该具有率先于后者的占有率可以具有默认值而前者不能。

相关问题