C++ 为构造函数中的变量设置默认值

C++ 为构造函数中的变量设置默认值,c++,C++,我写了这段代码,但在传递一个三参数构造函数时遇到了问题,该构造函数将第一个参数设置为房间号,第二个参数设置为房间容量,这是我遇到的问题。这三个部分是设置房价,将房间占用率设置为0。这是我编写的代码 #include "stdafx.h" #include <iostream> #include <iomanip> #include <string> using namespace std; class HotelRoom { private: strin

我写了这段代码,但在传递一个三参数构造函数时遇到了问题,该构造函数将第一个参数设置为房间号,第二个参数设置为房间容量,这是我遇到的问题。这三个部分是设置房价,将房间占用率设置为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;
}
是非法的,如果您提供默认值,则它们必须

事后没有争论 以下所有参数也必须具有默认值 要解决这个问题,请将您的占位符作为构造函数中的最后一个变量

HotelRoom::HotelRoom (string room, int cap, double rt, int occup=0 )
另一项说明:

仅在标题中提供默认值,重写默认值将在声明过程中出错

标题.h

HotelRoom(string,int,double,int occup=0);
imp.cpp

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

AFAIR,具有默认值的参数后面不能跟不带默认值的参数。在您的情况下,您应该在入住率之前确定入住率,后者可以有一个默认值,而前者不能。

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

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

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