预期的"("用于函数式铸造或类型构造

Expected '(' for function-style cast or type construction

本文关键字:类型 函数 用于      更新时间:2023-10-16

所以我正在尝试创建一个模拟医院病房的类房间,但它在我的构造函数中一直给我一个错误。 有时没有问题,但后来又回来了....此处的其他用户定义对象包括没有问题的 Patient 类和也没有问题的 LinkedList 模板类。

这是标题

class Room
{
public:
    Room();
    Room(int);
    static LinkedList<Room> createRooms();
    Patient patient;
    int roomNumber;
    bool operator==(const Room &other) const; //overload ==
    bool operator!=(const Room &other) const; //overload !=
    void operator=(const Room &other) const; //overload =

};

和菲共

#include "Room.h"
Room::Room();
Room::Room(int n)
{
    roomNumber= n;
    patient= Patient();
}
LinkedList<Room> Room::createRooms() {
    //create rooms up until ROOMS is reached
    LinkedList<Room> roomList;
    for(int i= 1; i < 11; i++){
        Room room= Room(100+i);
        roomList.push(room);
    }
    return roomList;
}
//Overload ==
bool Room::operator==(const Room &other)const{
    //compare each room's room number field
    return (this->roomNumber == other.roomNumber && this->patient == other.patient);
}
//Overload !=
bool Room::operator!=(const Room &other)const{
    return !(this == &other);
}
void Room::operator=(const Room &other)const{
    this->patient= other.patient;
    this->roomNumber= other.roomNumber;
}

问题出在 Room(int) 构造函数上。 Xcode 不断给我一条消息,说函数式强制转换或类型构造的预期"("

我不知道发生了什么

您显然忘记包含定义Patient的标头:

 #include "Patient.h"

或类似。

patient= Patient();

是冗余的,默认情况下,成员patient将被值初始化,并且

Room::Room();

不正确 - 您没有提供实现。

接下来,你的设计似乎有缺陷。你似乎暗示病人是房间的一部分,并选择了构图来做到这一点。但事实并非如此。如果房间是空的怎么办?您当前的设计尚未处理这种情况。

编辑:你的意思是:

return !(*this == other);

在你的超载operator!=

这看起来很奇怪:

   Room::Room();

我想你想要这个:

   Room::Room() {}

但是,您可能至少应该初始化成员变量,而不是使用空白构造函数。

您可以考虑在标头中将以下构造函数更改为"显式"(切勿滥用"显式",但有时需要时间)

explicit Room(int);

如果在你的代码位置中有一个类同时接受"int"或"const Room&"作为构造函数参数怎么办?

假设:

Hospital(int n); //Hospital constructor where n is number of rooms
Hospital(const Room& room); //Hospital constructor, hosptial made initially by only 1 room

在这种情况下没有显式构造函数

Hospital sanGrace(3);

编译器无法判断您是否有意

Hospital sanGrace(3);

Hospital sanGrace(Room(3));

使用"显式",您被迫编写

Hospital sanGrace(Room(3));

如果您想从 3 号房间创建 SanGrace's 医院。

这同样适用于患者类。