简体   繁体   English

从其他类访问变量(C ++)

[英]Accessing variables from other classes (C++)

I have been trying to access a series of integers from the main class, and then display them inside a method. 我一直在尝试从主类中访问一系列整数,然后在方法中显示它们。

However, I've been having a bit of trouble with this due to my own ineptitude with a language I've not been coding in for too long. 然而,由于我自己对一种我没有编写太长时间的语言的无能,我一直遇到一些麻烦。

After quite a bit of searching, I have been unable to find anything that can help me. 经过相当多的搜索,我一直无法找到任何可以帮助我的东西。 How would I go about doing this, if it's possible at all? 如果可能的话,我该怎么做呢?

#include "inventory.h"

inventory::inventory(){
    int maxhealth = 100;
    int maxmana = 0;

    int health = 100;
    int mana = 0;
    int level = 1;

    int agility = 1;
    int strength = 1;

    int healthpotions = 0;
    int manapotions = 0;

    int armourlevel = 0;
    int weaponlevel = 0;

    int crystals = 0;

    int gold = 0;
    int rock = 0;
    int wood = 0;
}

string inventory::getinv(){
    return inventory; //I know this sort of return thing won't work, just a placeholder until I figure out what to do.
}

This is what I have been using thus far, but I'm having a hard time even getting that to not display the "Member 'X' was not initialized in this constructor." 这就是我到目前为止所使用的,但是我很难在不显示“成员'X'在这个构造函数中没有初始化的情况下。” I'm clearly doing something quite wrong. 我显然做了一件非常错事。

Inventory.h: Inventory.h:

#ifndef INVENTORY_H_
#define INVENTORY_H_

#include <iostream>

class inventory{
private:
    int maxhealth;
    int maxmana;

    int health;
    int mana;
    int level;

    int agility;
    int strength;

    int healthpotions;
    int manapotions;

    int armourlevel;
    int weaponlevel;

    int crystals;

    int gold;
    int rock;
    int wood;

public:
    inventory();
    string getinv();
};
#endif /* INVENTORY_H_ */

EDIT: Thanks to the help so far I've been able to get rid of most of the errors. 编辑:感谢帮助到目前为止,我已经能够摆脱大多数错误。 The only one left is "..\\src\\zoria.cpp:1616:36: error: 'rock' was not declared in this scope" 剩下的唯一一个是“.. \\ src \\ zoria.cpp:1616:36:错误:'rock'未在此范围内声明”

You do not need the type in the constructor to access the member variables, otherwise the compiler would think that you are trying to declare new local variables. 您不需要构造函数中的类型来访问成员变量,否则编译器会认为您正在尝试声明新的局部变量。

Here is a basic correction for the inventory.cpp file: 以下是inventory.cpp文件的基本更正:

#include "inventory.h"

inventory::inventory(){ // this is the constructor
    maxhealth = 100;
    maxmana = 0;

    health = 100;
    mana = 0;
    level = 1;

    agility = 1;
    strength = 1;

    healthpotions = 0;
    manapotions = 0;

    armourlevel = 0;
    weaponlevel = 0;

    crystals = 0;

    gold = 0;
    rock = 0;
    wood = 0;
}

string inventory::getinv(){
    return "inventory"; //I know this sort of return thing won't work, just a placeholder until I figure out what to do.
}

Note the "" added to the placeholder ( return "inventory" ) to make it a valid string . 请注意添加到占位符的""return "inventory" )以使其成为有效string

Note: You cannot access the variable that is in a class directly without an object of the class, even if it is declared public ( static being the only exception). 注意:如果没有类的对象,则无法直接访问类中的变量,即使它被声明为public( static是唯一的例外)。 However you have declared all your member variables as private and will thus require getter and setter functions to access their values. 但是,您已将所有成员变量声明为private ,因此需要getter和setter函数来访问它们的值。

EDIT: 编辑:

Classes are like containers which contain things. 类就像包含东西的容器。 But just the definition of a class is just like a stencil which can be used to create objects of that type. 但只是类的定义就像模板一样,可用于创建该类型的对象。 The actual existence of the object occurs when you write inventory someobject; 当您编写inventory someobject;时,会发生对象的实际存在inventory someobject; .

Now every class has a special function called the constructor which goes by the name of the class itself and is called as soon as the an object of this class is declared. 现在每个类都有一个称为构造函数的特殊函数,该函数按类本身的名称进行操作,并在声明此类的对象后立即调用。 You can initialize all member variables of the class in the constructor. 您可以在构造函数中初始化类的所有成员变量。

To access the members of a class you have to use the . 要访问类的成员,您必须使用. dot operator. 点运算符。 Members have to be declared public if they need to be directly accessed outside the class' body. 如果成员需要在课堂外直接访问,则必须public会员。

So you change the class definitions like this: 所以你改变了这样的类定义:

inventory.h: inventory.h:

#ifndef INVENTORY_H_
#define INVENTORY_H_
class inventory{
public:

    int maxhealth;
    int maxmana;

    int health;
    int mana;
    int level;

    int agility;
    int strength;

    int healthpotions;
    int manapotions;

    int armourlevel;
    int weaponlevel;

    int crystals;

    int gold;
    int rock;
    int wood;

    inventory();
    void printinv();
};
#endif /* INVENTORY_H_ */

and

inventory.cpp: inventory.cpp:

#include "inventory.h"
#include <iostream>
using namespace std;

inventory::inventory()
{
    maxhealth = 100;
    maxmana = 0;

    health = 100;
    mana = 0;
    level = 1;

    agility = 1;
    strength = 1;

    healthpotions = 0;
    manapotions = 0;

    armourlevel = 0;
    weaponlevel = 0;

    crystals = 0;

    gold = 0;
    rock = 0;
    wood = 0;
}

void inventory::printinv(){
    cout << "LEVEL:           " << level << endl;
    cout << "HEALTH:          " << health << endl;
    cout << "MANA:            " << mana << endl;
    cout << "AGILITY:         " << agility << endl;
    cout << "STRENGTH:        " << strength << endl;
    cout << endl;
    cout << "HEALTH POTIONS:  " << healthpotions << endl;
    cout << "MANA POTIONS:    " << manapotions << endl;
    cout << endl;
    cout << "ARMOUR LEVEL:    " << armourlevel << endl;
    cout << "WEAPON LEVEL:    " << weaponlevel << endl;
    cout << "CRYSTALS:        " << crystals << endl;
    cout << endl;
    cout << "GOLD:            " << gold << endl;
    cout << "ROCK:            " << rock << endl;
    cout << "WOOD:            " << wood << endl;
}

Now declare the object of the class in main like: 现在在main声明类的对象,如:

inventory inv;

and access every member variable (such as maxhealth , maxmana , health , mana , level , agility , strength , healthpotions , manapotions , armourlevel , weaponlevel , crystals , gold , rock and wood ) like: 并访问每个成员变量(如maxhealthmaxmanahealth manamanalevelagilitystrengthhealthpotionsmanapotionsarmourlevelweaponlevelcrystalsgoldrockwood ),如:

inv.gold = 10;
inv.rock++;

etc. throughout the code. 等整个代码。

and to display the inventory replace all the redundant display code with: 并显示库存替换所有冗余显示代码:

inv.printinv();

everywhere. 到处。

See zoria.cpp here , I have done the changes for all display code and changed the variable accesses for: maxhealth , maxmana , health and healthpotions you also have to do it for the rest of the variables like: mana , level , agility , strength , manapotions , armourlevel , weaponlevel , crystals , gold , rock and wood . 在这里查看zoria.cpp ,我已经对所有显示代码进行了更改并更改了变量访问: maxhealthmaxmanahealthhealthpotions您还必须为其余变量执行此操作,例如: manalevelagilitystrengthmanapotionsarmourlevelweaponlevelcrystalsgoldrockwood

Hope this helps. 希望这可以帮助。 Tell if there are any more questions. 告诉我们是否还有其他问题。

In Inventory.h you define the member variables (maxhealth, maxmana etc) and in Inventory.cpp, you should declare them in its constructor. 在Inventory.h中,您定义成员变量(maxhealth,maxmana等),在Inventory.cpp中,您应该在其构造函数中声明它们。 The problem is that you're redeclaring them. 问题是你要重新声明它们。 Try removing the "int" from every variable in the constructor because you only need to specify the type when you define the variable. 尝试从构造函数中的每个变量中删除“int”,因为您只需在定义变量时指定类型。

A few points here: 这里有几点:

  1. In you constructor you are shadowing the instance variables by method-local re-definition of identically named variables. 在构造函数中,您通过方法本地重新定义具有相同名称的变量来遮蔽实例变量。 Please, look up on how to initialize instance member variables in constructors. 请查看如何在构造函数中初始化实例成员变量。

  2. You try to implicitly convert an instance of your inventory class into a std::string with the signature of your getinv() method, but you have not defined any operator for this kind of conversion. 您尝试将inventory类的实例隐式转换为带有getinv()方法签名的std::string ,但您尚未为此类转换定义任何运算符。

  3. (probably related to (2)) From the error you posted, I assume you are using getinv() something along the line of (可能与(2)相关)从你发布的错误中,我假设你正在使用getinv()

     inventory my_inventory{}; int inv = my_inventory.getinv(); 

    This will not work as there is no implicit conversion from std::string to int defined. 这不起作用,因为没有从std::stringint定义的隐式转换。 Change the return type of inventory::getinv() to int and return an actual int there. inventory::getinv()的返回类型更改为int并返回实际的int

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM