【问题标题】:C++: How to start an array in a class?C++:如何在一个类中开始一个数组?
【发布时间】:2014-01-20 23:24:07
【问题描述】:

我一直在尝试通过创建基于文本的游戏来学习 C++。在这个游戏中,我创建了一个 MapHandler,它有一个网格(多维数组,5x5,int)。我希望能够在调用该类时将其传递给网格,但我似乎无法做到。

我的问题是:如何从外部为类中的数组设置值?

我写了一些代码来复制我的错误:

// ConsoleApplication2.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <string>

using namespace std;

class Person {
    public:
        int age;
        string characteristics[5];
        Person();
};

int _tmain(int argc, _TCHAR* argv[])
{
    string traits[5] = {'Stubborn','Ambitious','Smart','Emotional','Extrovert'};
    Person Bob;

    Bob.age = 18;
    Bob.characteristics = traits;

    system("Pause");
    return 0;
}

【问题讨论】:

  • “我一直在尝试通过创建基于文本的游戏来学习 C++。” - 尝试阅读介绍性书籍。
  • 使用std::array
  • 字符串应该用双引号而不是单引号引用:'Stubborn'
  • 你应该正确开始并使用std::vector而不是数组。

标签: c++ arrays oop


【解决方案1】:

在 C++ 中,普通数组不是一等的,即它们不能被复制。改用std::array 会让您受益。

【讨论】:

    【解决方案2】:

    问题是您无法复制原始数组(即int a[5], b[5]; b=a;)。您必须逐个元素地复制它们:

    for(int i = 0; i < 5; ++i)
        Bob.characteristics[i] = traits[i];
    

    甚至更好:

    #include <algorithm>
    
    
    // ...
    
    std::copy(traits, traits+5, Bob.characteristics);
    

    【讨论】:

      猜你喜欢
      • 2020-07-09
      • 1970-01-01
      • 2012-02-02
      • 2014-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-01
      相关资源
      最近更新 更多