和 之间有什么区别?和->在 C++ 中调用方法时
你能告诉我a和a之间的区别吗?和->调用 C++ 中的方法。
这段代码使用两种调用方法都可以正常工作。
#include <iostream>
using namespace std;
class myclass
{
public:
string doSomething();
};
string myclass::doSomething()
{
return "done something\n";
}
int main (int argc, const char * argv[])
{
myclass c;
std::cout << c.doSomething();
myclass *c2;
std::cout << c2->doSomething();
return 0;
}
我不明白这两个调用之间的区别?他们都工作吗?
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 something\n";
}
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
相当于:
即在调用方法之前取消引用指针。
如需更多帮助,请参阅 Alf Steinbach 的指针教程。
is equivalent to:
i.e. the pointer is being de-referenced before calling the method.
Check out Alf Steinbach's pointer tutorial for more help.
箭头运算符用于从指向对象实例的指针调用方法。
点运算符用于从对象实例的引用或本地定义的对象上调用方法。
如果颠倒两个示例中的运算符,您的代码将无法编译。
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
未初始化。您需要编写
c2->doSomething()
在语义上等同于(*c2).doSomething()
,而它又与c.doSomething 相同()
编辑
查看 Alf Steinbach 的指针教程
This is undefined behaviour.
c2
is not initialized.You needed to write
c2->doSomething()
is semantically equivalent to(*c2).doSomething()
which in-turn is same asc.doSomething()
EDIT
Check out Alf Steinbach's pointer tutorial
不,正如发布的那样,它不会工作,因为您没有初始化指针 c2。
至于语法:请参考任何一本C++的入门书籍,里面都会对此进行解释。
最简短的版本是,箭头运算符
->
是(*c2).doSomething();
的快捷形式No, as posted, it won't work, because you do not initialize the pointer c2.
As for the syntax: Please refer to any introductory book on C++, which will explain this.
The short very version is, that the arrow operator
->
is a shortcut form for(*c2).doSomething();