You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何无需遍历判断获取C++类中标记为当前武器的对象

解决方法

你可以在Weapon类中添加一个静态指针成员,用来跟踪当前选中的武器。这样在创建对象时,只要isCurrentWeapon为true,就自动让这个指针指向该对象,同时确保同一时间只有一个当前武器。这种方式不需要手动遍历所有对象就能直接获取当前武器。

修改后的完整代码

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

class Weapon {
public:
    string name;
    int damage;
    bool isCurrentWeapon;
    // 静态指针,跟踪当前武器
    static Weapon* currentWeapon;

public:
    Weapon(string n, int d, bool iCW) 
        : name(n), damage(d), isCurrentWeapon(iCW) {
        if (isCurrentWeapon) {
            // 如果之前有当前武器,将其标记为非当前
            if (currentWeapon != nullptr) {
                currentWeapon->isCurrentWeapon = false;
            }
            // 更新当前武器指针
            currentWeapon = this;
        }
    }
};

// 初始化静态指针为nullptr
Weapon* Weapon::currentWeapon = nullptr;

int main() {
    Weapon sword("Sword", 30, true);
    Weapon dagger("Dagger", 10, false);
    
    // 直接通过静态指针获取当前武器名称
    cout << "Welcome to the Weapon Shop! Your current weapon is: " 
         << Weapon::currentWeapon->name << endl;
    return 0;
}

关键说明

  • 静态指针currentWeapon:属于整个Weapon类,而非某个实例,所以能全局跟踪当前选中的武器。
  • 构造函数逻辑:当创建一个标记为当前武器的对象时,先检查是否已有当前武器,若有则将其isCurrentWeapon设为false,避免多个当前武器共存,然后把静态指针指向新的当前武器。
  • 直接访问:在main函数中无需遍历,直接通过Weapon::currentWeapon就能获取当前武器的信息。

另一种可选方案(用标准库算法,无需手动写if遍历)

如果你不想用静态指针,也可以把所有武器对象存入容器(比如vector),然后用std::find_if自动查找,不用自己写循环和if判断:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;

class Weapon {
public:
    string name;
    int damage;
    bool isCurrentWeapon;

public:
    Weapon(string n, int d, bool iCW) 
        : name(n), damage(d), isCurrentWeapon(iCW) {}
};

int main() {
    vector<Weapon> weapons = {
        Weapon("Sword", 30, true),
        Weapon("Dagger", 10, false)
    };
    
    // 用std::find_if查找isCurrentWeapon为true的对象
    auto it = find_if(weapons.begin(), weapons.end(), 
        [](const Weapon& w) { return w.isCurrentWeapon; });
    
    if (it != weapons.end()) {
        cout << "Welcome to the Weapon Shop! Your current weapon is: " 
             << it->name << endl;
    }
    return 0;
}

这种方式虽然底层还是遍历,但你不用手动写循环和if判断,符合你“无需逐个使用if语句遍历”的需求。

内容的提问来源于stack exchange,提问作者Spaghetti

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 08:17:16