[英]What is the difference between a void function() and a void ClassName::function() in C++?
What is the difference between them? 它们之间有什么区别? Are they both one-per object? 它们都是一个对象吗? (beginner question) (初学者问题)
The void function can be called without an instance of any specific class... ie just call... 可以在没有任何特定类的实例的情况下调用void函数。
function()
For ClassName::function()
you need to call it on a specific object of type ClassName
: 对于ClassName::function()
您需要在ClassName
类型的特定对象上调用它:
ClassName my_class;
my_class.function();
When called, ClassName::function()
will have a hidden implicit function argument this
, which can be used inside the function body. 调用时, ClassName::function()
将具有一个隐藏的隐式函数参数this
,可以在函数体内使用。 It is a pointer to the ClassName
object on which ClassName::function
has been invoked. 它是指向在其上调用ClassName::function
的ClassName
对象的指针。 You can also access other class members. 您还可以访问其他班级成员。
Another related difference is that you can take a pointer to function()
and call it at any time, whereas when you take a pointer-to-member-function to ClassName::function()
you'll also need a specific ClassName
object at the time you want to run the function. 另一个相关的区别是您可以随时获取指向function()
的指针并随时调用它,而当您获取指向ClassName::function()
的成员函数的指针时,您还需要一个特定的ClassName
对象您要运行该功能的时间。
A namespace scope function can be called from anywhere without a object: 可以在没有对象的任何地方调用名称空间作用域函数:
int foo();
void bar() {
int x = foo();
}
A member object needs an instance to be called, which is implied within the context of another member function: 成员对象需要调用一个实例,该实例隐含在另一个成员函数的上下文中:
struct B {
int foo();
int fred() {
if (true) {
return foo(); // OK, local object implied
}
return n; // member function can also access member variables
}
static int george(); // static members can be called without instances!
int n;
};
void baz() {
B b;
int x = B::george(); // static class members don't need instances.
int y = b.foo(); // member function on object OK
//int z = foo(); // XXX: this wouldn't compile
}
void ClassName::function()
is call to a function inside your class. 是在您的类中调用一个函数。 member function . 成员函数 。 and should be called by using object of your class. 并应通过使用您的类的对象来调用。 while, 而,
void function()
is just a function and can be called without object. 只是一个函数,可以在没有对象的情况下调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.