I need some help here, could you tell me how I can get p2 variable content? I can get variables through t1 and p1 but I want to use p2 to get health and mana values.
#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;
}
Use
cout << (*p2)->health << endl;
The *
has two meanings: to declare a pointer and to dereference a pointer. But since ->
has higher precedence than *
you need to put *p2
into backets.
Your example suggests that you are looking for a single operator that dereferences two times at once. There is none in C++.
Two ways to achieve what you want. The first has already been mentioned and goes
std::cout << (*p2)->health << std::endl;
The second can be found by noting that p1->health
is equivalent to (*p1).health
. Hence, (*p2)->health
is equivalent to (**p2).health
. In a row:
std::cout << t1.health << std::endl;
std::cout << (*p1).health << std::endl;
std::cout << (**p2).health << std::endl;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.