小编M4G*_*I3R的帖子

如何使用 C++ 中的函数永久更改类属性值?

我用 C++ 编写了一个包含 2 个类的程序。基本上“HeroList”只是“Hero”元素的向量。现在我想更改每个英雄给出的值(在函数“change”中)。但这不起作用。仅当我直接使用“英雄”对象作为参数调用该函数时,它才有效(尝试 1)。但是当我使用“heroList”元素作为参数(尝试2)时,它仅在函数处于活动状态期间更改值,并且当其结束时它们会重置。我猜这与引用的使用有关,但我找不到我的错误。

#include <iostream>
#include <string>
#include <vector>

using namespace std;

class Hero
{

private:
    string name;        //Hero-Name
    int value;          //Hero-Value

public:

    Hero(string name = "std", int value = 0) {

        this->name = name;
        this->value = value;
    }                           

    void setValue(int i) {
        if (i == 1) {                   //If 1 -> value - 1
            if (value != 0) {           //If value already 0 nothing happens
                value = value - 1;
            }
        }
        if (i == 2) { …
Run Code Online (Sandbox Code Playgroud)

c++ attributes reference class function

4
推荐指数
2
解决办法
3508
查看次数

标签 统计

attributes ×1

c++ ×1

class ×1

function ×1

reference ×1