> in calling a Method in C++
Can you tell me the difference between a . and -> call to a method in C++.
This code works fine, using both calling methods.
#include <iostream>
using namespace std;
class myclass
{
public:
string doSomething();
};
string myclass::doSomething()
{
return "done somethingn";
}
int main (int argc, const char * argv[])
{
myclass c;
std::cout << c.doSomething();
myclass *c2;
std::cout << c2->doSomething();
return 0;
}
I don't understand the different between the 2 calls? they both work?
The arrow operator is meant for calling a method from a pointer to an instance of an object.
The dot operator is meant for calling a method from a reference to an instance of an object, or on a locally defined object.
Your code would not compile if you reversed the operators on the two examples.
c2->doSomething();
is equivalent to:
(*c2).doSomething();
ie the pointer is being de-referenced before calling the method.
Check out Alf Steinbach's pointer tutorial for more help.
myclass *c2;
std::cout << c2->doSomething();
This is undefined behaviour. c2
is not initialized.
You needed to write
myclass *c2 = &c;
c2->doSomething();
c2->doSomething()
is semantically equivalent to (*c2).doSomething()
which in-turn is same as c.doSomething()
EDIT
Check out Alf Steinbach's pointer tutorial
链接地址: http://www.djcxy.com/p/40584.html上一篇: 关于argc(不知道它是什么意思)
下一篇: >在C ++中调用Method