c++ - 如何在main之外的函数中访问数组?

标签 c++ class

我正在尝试创建一个打印商店库存的程序。我在 getInventory 函数中打印出我的对象的变量。但是,当我尝试在 getStore 函数中打印出整个库存时,它什么也不返回。我觉得我的指针正确指向我的数组是个问题,但我不确定。

#include <iostream>
#include <string>

class Weapon
{
private:
    std::string nameWeapon, messageUsed;
    bool ownedWeapon;
    double weaponCost;
    int numberUses;

public:
    //Default constructor
    Weapon() 
    {
        nameWeapon = "weapon name";
        messageUsed = "weapon sound";
        weaponCost = 0;
        ownedWeapon = false;
        numberUses = 1;
    }
    //Non-Default Constructor
    Weapon(std::string nW, std::string mU,double wC,bool oW, int nU )
    {
        nameWeapon = nW;
        messageUsed = mU;
        weaponCost = wC;
        ownedWeapon = oW;
        numberUses = nU;
    }
    void getInventory()
    {
        std::cout << nameWeapon << "\t" << messageUsed << "\t" << weaponCost << "\t" << ownedWeapon << "\t" << numberUses << "\n";
    }
    void getStore(Weapon* weaponArray)
    {
        std::cout << "Name" << "\t" << "Sound" << "\t" << "Price" << "\t" << "Owned";
        for (int i = 0; i < 9; i++)
        {
              weaponArray[i].getInventory();
        }
    }
};
int main()
{
    Weapon weaponArray[9]{};
    weaponArray[0] = Weapon("Broad Sword","Clang!",50,false,3);
    weaponArray[1] = Weapon("Champions Sword","Swoosh!",99.99,false,5);
    weaponArray[2] = Weapon("Dagger","Ding!",12.25,false,1);
    weaponArray[3] = Weapon("Poisin Dagger","Shh",18.50,false,1);
    weaponArray[4] = Weapon("Sturdy Dagger","Gronk!",14.75,false,3);
    weaponArray[5] = Weapon("Short Bow","T'wang!",35.75,false,3);
    weaponArray[6] = Weapon("Champions Bow","Swoop!",90.15,false,5);
    weaponArray[7] = Weapon("Champions Axe","Bash!",110.11,false,6);
    weaponArray[8] = Weapon("Throwing Axe","Bonk!",25.75,false,2);

    void getStore();

    system("pause");
    return 0;
}

最佳答案

void getStore();

这是一个函数 stub 。它声明了一个函数 getStore,它不接受任何参数并且不返回任何内容以供稍后实现。这几乎肯定是一个错字。

此外,因为 void getStore(Weapon* weaponArray) 在 Weapon 类中,你必须在武器上调用它,这看起来不对。您可能打算这样做:

class Weapon {
    // ...
};

void getStore(Weapon* weaponArray, unsigned sz)
{
    std::cout << "Name" << "\t" << "Sound" << "\t" << "Price" << "\t" << "Owned";
    for (unsigned i = 0; i < sz; i++)
    {
          weaponArray[i].getInventory();
    }
}

int main()
{
    Weapon weaponArray[9]{};
    weaponArray[0] = Weapon("Broad Sword","Clang!",50,false,3);
    //...

    getStore(weaponArray, 9);
}

关于c++ - 如何在main之外的函数中访问数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58964588/

相关文章:

c++ - 关于消息队列与共享内存在这种情况下的适用性或适用性

java - java中的getType()和getClass()有什么区别?

C# - 缩短函数调用

javascript - 如何在 JavaScript 中实现类自由继承(Crockford 风格)

类中的Android Gesture Detection,调用方法

c++ - 在不使用 ignore() 的情况下读取二进制文件(C++)时忽略 N 个字节?

带有 throw(...) 的 C++ 方法声明

c++ - 使用 Boost adjacency_list 执行 connected_components where VertexList=listS

c++ - 取消引用 50% 出界指针(数组的数组)

java - 在java中的3个类中调用另一个类中的方法