-1

我的任务是编写一个代表骑士的类(名称,等级,xp),他最多可以有10个项目(它必须是另一个类)(item_name,value)

所以,我想做这样的事情,但是有了课程,我怎么能做到呢?

struct item
{
    char itemName[21];
    int value;
};

struct knight
{
   char name[21];
   int xp;
   int level;
   struct item cucc[10];
};
4

3 回答 3

1

如何在 C++ 中将类放在一起?

好吧,只要嵌套它们,如果这就是你的意思:

struct knight
{
    struct item
    {
        char itemName[21];
        int value;
    };

    char name[21];
    int xp;
    int level;
    item cucc[10]; // Notice, that the struct keyword isn't necessary here
};

更新:(在更好地考虑了您实际要问的问题之后)

所以,我想做这样的事情,但是有了课程,我怎么能做到呢?

首先,structs 是 C++ 中的类。但是您的意思可能是“我如何将这些数据封装到类中并在它们之间建立定向关联?”

在这种情况下,我会选择这样的东西:

class item
{
public:
    // The constructor to set an item's name and value
    item(std::string name, int value);
    // Supposing your item's names and values don't change,
    // so only getters on the class's interface
    std::string get_name() const;
    int get_value() const;
private:
    // Member variables are private (encapsulated).
    std::string itemName;
    int value;
};

// Skipping member function definitions. You should provide them.

class knight
{
public:
    // The constructor to set a knight's name
    knight(std::string name);
    // Supposing the name is unchangeable, only getters on the interface
    std::string get_name() const;
    // ...
    // What goes here very much depends on the logic of your application
    // ...
private:
    std::string name;
    int xp;
    int level;
    std::vector<item> cucc; // If you need reference semantics, consider
                            // std::vector<std::shared_ptr<item>> instead
};

// Skipping member function definitions. You should provide them.
于 2013-02-21T19:38:12.180 回答
1

所以,我想做这样的事情,但是有了课程,我怎么能做到呢?

你已经有了。关键字在 C++中struct定义了一个类,就像class关键字一样;唯一的区别是,对于使用struct.

另外,请注意,在item类的定义之后,struct itemitem命名完全相同的类型;C++ 没有 C 所具有的类型和结构标记之间的分离。

有关详细信息,请参阅 C++11 标准的第 9 节(或免费提供的n3337 最终工作草案)。特别是,9.1 类名称以:

类定义引入了一种新类型。[例子:

struct X { int a; };

它继续解释这个声明将类名引入范围,struct X根据是否X在范围内等阐明其本身的含义。

struct和之间的区别class稍后在11 成员访问控制11.2 基类和基类成员的可访问性中讨论:

默认情况下,使用关键字 class 定义的类的成员是私有的。默认情况下,使用关键字 struct 或 union 定义的类的成员是公共的。

…</p>

在基类没有访问说明符的情况下,当派生类使用 class-key 定义时假定为 public,而当使用class - key struct定义类时假定为 private 。 class

于 2013-02-21T19:42:16.117 回答
0

类和结构(我在语义上使用这些术语,而不是在语法上——见下文)可以任意嵌套:

#include <string>
#include <array>

struct Knight {
  struct Item {
    std::string name;
    int value;
  };

  std::string name;
  int xp;
  int level;
  std::array<Item,10> cucc; // us an `std::vector` if the size is *not* fixed  
};

关于类:在语法上,结构和类之间几乎没有区别,但是应该区分您想要的对象是什么。如果它只是数据的聚合,它在概念上是一个结构,这应该通过使用struct关键字来表示。如果是智能数据结构,通过成员函数管理自己的私有成员,从概念上讲就是一个类,所以一般用class关键字声明。

但是,在语法上classstruct仅更改成员和父类型的默认可见性(class隐式privatestruct隐式public)。

于 2013-02-21T19:42:09.220 回答