gpt4 book ai didi

C++ 对象指针

转载 作者:行者123 更新时间:2023-11-27 23:54:33 25 4
gpt4 key购买 nike

我需要一些帮助,你能告诉我如何获取 p2 变量内容吗?我可以通过 t1 和 p1 获取变量,但我想使用 p2 来获取健康值和法力值。

#include <iostream>

using namespace std;

class Mage{
public:
int health;
int mana;
Mage(int health, int mana){
this->health = health;
this->mana = mana;
}
};

int main(){

Mage t1 = Mage(1,1);
Mage *p1 = &t1;
Mage **p2 = &p1;

cout << t1.health << endl;
cout << p1->health << endl;
cout << "how to print variable content with p2?" << endl;

return 0;
}

最佳答案

使用

cout << (*p2)->health << endl;

* 有两个含义:声明一个指针和解引用一个指针。但是由于 -> 的优先级高于 *,因此您需要将 *p2 放入 backets。

关于C++ 对象指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43593218/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com