【问题标题】:C++ assign values to a static array in a ClassC ++将值分配给类中的静态数组
【发布时间】:2016-02-23 22:59:21
【问题描述】:
  • 我是 C++ 新手。编译器抱怨以下行: inv.inventory[0] = "书籍"。请帮助我如何分配值 到 Class 中的静态数组。

// 类声明

#include <iostream>
#include <iomanip>
#include <string>
using namespace std;

class Items
{
private:
    string description;
public:
    Items()
    {
        description = ""; }

    Items(string desc)
    {
        description = desc;}

    string getDescription() { return description; }

};
class InventoryItems {
public:
    static Items inventory[5];

};
// main function
int main()
{
    const int NUM = 3;
    InventoryItems inv;
    inv.inventory[0] = "Books";

    for (int i = 0; i < NUM; i++)
    {
        cout <<  inv.inventory[i].getDescription() << endl;
    }


    return 0;
}

我遇到以下错误:

invMain.cpp:31: 错误: InventoryItems::inventory[0] = "Books" 中的 operator= 不匹配 invMain.cpp:7: 注意:候选者是:Items& Items::operator=(const Items&)

【问题讨论】:

    标签: c++ arrays static


    【解决方案1】:

    这里有几个问题:

    static Items inventory[5];
    

    static 表示对于所有InventoryItems,只有一个inventory。不幸的是,它并没有为所有编译器分配空间。 OP可能会看到

    对 `InventoryItems::inventory' 的未定义引用

    您可以使用

    分配存储空间
    class InventoryItems {
    public:
        static Items inventory[5];
    
    };
    
    Items InventoryItems::inventory[5]; // needs to be defined outside the class
    

    另一个大问题是你试图把方钉塞进圆孔里,然后得到一些类似

    的东西

    错误:'operator=' 不匹配

    "Books"const char *,而不是项目。 const char * 很容易转换为 string,因为有人花时间编写完成这项工作的函数。你也必须这样做。

    你可以把它变成一个Items然后赋值

    inv.inventory[0] = Items("Books");
    

    这会创建一个临时的Items,然后在复制后将其销毁。有点贵,因为你有一个构造函数和一个析构函数被调用只是为了复制一个 dang 字符串。

    你也可以这样调用:

    InventoryItems::inventory[0] = Items("Books");
    

    因为所有InventoryItems 共享相同的inventory,所以您不必创建InventoryItems 即可获得inventory

    如果你不想创建和销毁额外的对象,你可以为 Items 写一个赋值运算符,它接受一个字符串

    Items & operator=(string desc)
    {
        description = desc;
        return *this;
    }
    

    现在两个

    InventoryItems::inventory[0] = Items("Books");
    

    InventoryItems::inventory[1] = "Pizza";
    

    工作。

    你也可以在Items创建一个setter函数

    void setDesc(string desc)
    {
        description = desc;
    }
    

    现在您可以花与operator= 差不多的费用

    InventoryItems::inventory[2].setDesc("Beer");
    

    由您决定。我个人喜欢这种情况下的二传手。你在做什么比= 更明显,而且比临时变量更便宜。

    【讨论】:

      【解决方案2】:

      你还没有说错误是什么。我在 Visual Studio 2015 中编译了相同的代码并得到“二进制 '=':未找到运算符”。

      所以问题是您没有为 Items 类定义 operator = 。你需要这个,因为 Items 不等同于字符串,即使此时它只包含一个字符串。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-12-18
        • 1970-01-01
        • 1970-01-01
        • 2022-07-21
        • 1970-01-01
        • 2020-07-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多