#include <iostream> using namespace std; class Person{ public: Person(){ }; void speak(){ cout<<"Helloworld"<<endl; }; }; int main() { Person p; p->speak(); //error p.speak(); return 0; }
为什么这里面会出现错误?也就是说在什么情况下使用 -> ?
如果把里面的代码换成:
Person *p; p->speak();//right 这里面是不是默认实例化了一个类? p.speak();//error return 0;
求解惑,求指导。
伊谢尔伦2017-04-17 11:04:31
Basic syntax knowledge, -> is used for class instances of pointer types. In addition, in the second case, it can only pass the compilation, but it will definitely cause a segment fault when running. The reason is that the constructor will not be called at this time. When you use a pointer, you must create a new object. I won’t say more. Yeah, it’s very tiring to grab a phone at the airport and reply haha
黄舟2017-04-17 11:04:31
The pointer type has an overloaded -> operator, so it is no problem to use -> for pointers, and the . operator for objects.
Of course, if the object is overloaded -> can also be used -> It depends on whether you have implemented it yourself. If not, it will definitely not work.
PHP中文网2017-04-17 11:04:31
a->someMethod() is generally equivalent to (*a).someMethod()
. is used for instances, -> is used for pointers. . .
But only in general.