C++ 将对象放置在数组中

C++ Placing objects in arrays

本文关键字:数组 对象 C++      更新时间:2023-10-16

正在尝试将对象放在数组列表中,弹出了 3 个错误。我查看了论坛,有一个与我类似的问题,但我认为它不适用于我的情况。这是我的代码:

测试中.cpp(主文件)

#include <iostream>
#include "House.h"
using namespace std;
House HouseArray[2];
int main()
{
    string toPrint;
    House Kubo("Kubo", 2);
    HouseArray[0] = Kubo;
    toPrint = HouseArray[0].GetHouseName;
    cout <<toPrint<< endl;
}

在房子里.cpp

#include "House.h"
#include <iostream>

House::House(string a, int h)
{
    Name = a;
    Health = h;
}
void House::DamageHouse(int d) {
    Health -= d;
    cout << "Your " << Name << " has " << Health << " left."<<endl;
}
int House::GetHouseHealth() {
    return Health;
}
string House::GetHouseName() {
    string returning = Name;
    return returning;
}
House::~House()
{
}

在房子里。

#include <string>
using namespace std;
class House
{
    string Name;
    int Health;
public:
    House(string a, int h);
    int GetHouseHealth();
    void DamageHouse(int d);
    string GetHouseName();
    ~House();
};

错误:

  1. 错误 C2512 'House':第 9 行中没有适当的默认构造函数可用测试.cpp
  2. 错误 C3867 'House::GetHouseName':非标准语法;使用 '&'创建指向的指针杆件测试.cpp在第 16 行
  3. 错误 C2679 二进制"=":找不到右手的运算符类型为"重载函数"的操作数(或没有可接受的操作数转换)测试.cpp在第 16 行
  1. 如果要创建这样的数组,则需要一个默认构造函数: House HouseArray[2];编译器需要知道如何创建空House,以便可以初始化初始数组。因此,将类似以下内容的内容添加到House.h House() { Name = ""; Health = 0; }

  2. 要在类上调用函数,您需要添加大括号: toPrint = HouseArray[0].GetHouseName();

  3. 我怀疑以上也可以解决这个问题。