C++ 将对象放置在数组中
C++ Placing objects in arrays
我正在尝试将对象放在数组列表中,弹出了 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();
};
错误:
- 错误 C2512 'House':第 9 行中没有适当的默认构造函数可用测试.cpp
- 错误 C3867 'House::GetHouseName':非标准语法;使用 '&'创建指向的指针杆件测试.cpp在第 16 行
- 错误 C2679 二进制"=":找不到右手的运算符类型为"重载函数"的操作数(或没有可接受的操作数转换)测试.cpp在第 16 行
-
如果要创建这样的数组,则需要一个默认构造函数:
House HouseArray[2];
编译器需要知道如何创建空House
,以便可以初始化初始数组。因此,将类似以下内容的内容添加到House.hHouse() { Name = ""; Health = 0; }
-
要在类上调用函数,您需要添加大括号:
toPrint = HouseArray[0].GetHouseName();
-
我怀疑以上也可以解决这个问题。
相关文章:
- 销毁C++中动态分配的内存(数组对象)
- 数组对象的生存期是否在重用其元素存储时结束?
- 为什么顶点数组对象会导致错误?
- 具有纯虚函数和指针数组对象类型的父类的指针数组
- 这是使用构造函数初始化数组对象的最佳方法吗?
- OpenGL 顶点数组对象与 tinyobjloader
- 将数组/对象/结构列表从C#库中传递给C MFC应用程序
- C++ RapidJson 帮助反序列化数组对象
- ptrdiff_t可以表示指向同一数组对象元素的指针的所有减法吗?
- 检查成员函数是否返回临时对象或数组对象
- 为什么 std::variant 不能容纳数组对象类型,而联合可以?
- 当数组对象以函数参数传递时,为什么复制构造函数会自称
- 如何使用箭头指针打印出一类数组对象,这些对象中有多个分数
- C++17 std::shared_ptr<> 类数组对象的重载运算符 []
- 添加两个具有运算符重载的数组对象,从而导致分段错误
- opengl:两个不同的矢量可以绑定到同一个顶点数组对象吗
- 使用相同的数据填充数组对象或使用指针
- 方法用于最快的分配,并且不需要将动态大小的数组对象作为局部变量
- 如何将2d数组对象传递给c++中的函数
- ReferenceTable溢出(jni-android),数组对象释放