小编Zom*_*gie的帖子

如何在单个声明中设置继承的C++类/结构变量

是否有一种方法可以用一行代码声明一个具有继承变量的新对象?例:

#include <iostream>

using namespace std;

struct item_t {
    string name;
    string desc;
    double weight;
};

struct hat_t : item_t
{
    string material;
    double size;
};

int main () 
{
    hat_t fedora; // declaring individually works fine
    fedora.name = "Fedora";
    fedora.size = 7.5;

    // this is also OK
    item_t hammer = {"Hammer", "Used to hit things", 6.25}; 

    // this is NOT OK - is there a way to make this work?
    hat_t cowboy = {"Cowboy Hat", "10 gallon hat", 4.5, …
Run Code Online (Sandbox Code Playgroud)

c++ variables inheritance struct class

1
推荐指数
1
解决办法
1264
查看次数

在另一个文件中引用C++ struct对象?

我正在努力让正在进行的游戏更加模块化.我希望能够在游戏中声明所有room_t对象的单个数组(room_t rooms []),将其存储在world.cpp中并从其他文件中调用它.

下面的截断代码不起作用,但就我所知.我想我需要使用extern但是无法找到一个正常工作的方法.如果我尝试在头文件中声明数组,我会得到一个重复的对象错误(因为每个文件都调用world.h,我假设).

main.cpp中

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

int main()
{
    int currentLocation = 0;
    cout << "Room: " << rooms[currentLocation].name << "\n";
    // error: 'rooms' was not declared in this scope
    cout << rooms[currentLocation].desc << "\n";    
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

world.h

#ifndef WORLD_H
#define WORLD_H
#include <string>


const int ROOM_EXIT_LIST = 10;
const int ROOM_INVENTORY_SIZE = 10;

struct room_t
{
    std::string name;
    std::string desc;
    int exits[ROOM_EXIT_LIST];
    int inventory[ROOM_INVENTORY_SIZE];
};  

#endif
Run Code Online (Sandbox Code Playgroud)

world.cpp

#include "world.h"

room_t rooms[] = {
  {"Bedroom", "There …
Run Code Online (Sandbox Code Playgroud)

c++ variables struct extern

1
推荐指数
1
解决办法
2075
查看次数

标签 统计

c++ ×2

struct ×2

variables ×2

class ×1

extern ×1

inheritance ×1