开发者

How to use a pointer's methods in C++?

开发者 https://www.devze.com 2023-04-09 09:36 出处:网络
I have a code in which I use a pointer to a class that I made. As an example lets say I have a Person method, and each Person had a name. Now lets say I use a pointer for a person like

I have a code in which I use a pointer to a class that I made. As an example lets say I have a Person method, and each Person had a name. Now lets say I use a pointer for a person like

Person& * person_;

Now lets say I'm trying to get the name of the person using the pointer I have. If I do something as simple as

person_.getName()

It will return an error saying that it's a non-class type.

My question is: if all I have is the pointer to work with, how do I use 开发者_高级运维the methods of the class it's pointing to?


I don't how you got the compiler to even accept Person& * person_, since that's a meaningless declaration (there are no pointers to references). Assuming you actually used Person* person_, simply use the -> operator: person_->getName().


You use the pointer notation:

person_->getName()

-> is what you want.


It should be person_->getName();


person_->getName() is shorthand for (*person_).getName(). Both will work. Also, as @Marcelo pointed out, it should be Person& * person_;


person_->getName() is what you should be using.

You can read about it on cplusplus.com

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号