[英]Returning a pointer from member function c++
If I want to return a pointer from a member-function I first thought the syntax should look like the following: 如果我想从成员函数返回一个指针我首先认为语法应如下所示:
char SecondClass:: *getName() {
return this->name;
}
But I got an error-message in Eclipse that it couldn't solve the field "name". 但是我在Eclipse中收到一条错误消息,它无法解决字段“name”。 Somehow it becomes hidden in this case. 在某种程度上它会隐藏在这种情况下。
The correct solution is this 这是正确的解决方案
char *SecondClass:: getName() {
return this->name;
}
That is putting an * before the classname instead of the function-name. 那就是在classname之前加上*而不是function-name。
So my question is: why is the first function not working and what is the difference between these implementations of returning pointers from member-functions? 所以我的问题是:为什么第一个函数不起作用,这些从成员函数返回指针的实现之间有什么区别?
This has nothing to do with pointers. 这与指针无关。 The method is called SecondClass::getName()
and it returns a char*. 该方法称为SecondClass::getName()
,它返回一个char *。 So you can write 所以你可以写
char* SecondClass::getName()
or 要么
char *SecondClass::getName()
but you can't put the * between the class name and the method name. 但是你不能把*放在类名和方法名之间。
char SecondClass:: *getName()
is a very different function from char *SecondClass:: getName()
. char SecondClass:: *getName()
是一个与char *SecondClass:: getName()
完全不同的函数。
The first one not a member function of SecondClass
or any other class, thus you cannot refer to this
inside it. 第一个不的成员函数SecondClass
或其他任何类,所以你不能参考this
里面。 It happens to return a special kind of pointer called pointer-to-member . 它恰好返回一种称为指向成员的特殊指针。 Its type is spelled char SecondClass:: *
and it is a pointer to a member of type char
in class SecondClass
. 它的类型为拼写char SecondClass:: *
,它是指向类SecondClass
char
类型成员的指针。 You probably don't want to know any of this just yet. 你可能还不想知道这些。
The ssyntax you want is return-type function-name parameter-list . 你想要的ssyntax是return-type function-name parameter-list 。 You want to define a function named SecondClass::getName
that returns a char *
and takes no parameters, thus char *SecondClass::getName()
. 您想要定义一个名为SecondClass::getName
的函数,它返回一个char *
并且不带参数,因此char *SecondClass::getName()
。
In c++, the signature of a member function is [returnType] [ClassName]::functionName{} 在c ++中,成员函数的签名是[returnType] [ClassName] :: functionName {}
the star is part of the return type, which is char*, or pointer to a char. 星号是返回类型的一部分,它是char *,或指向char的指针。 Your first way of declaring a function is just not valid c++. 你声明一个函数的第一种方法是无效的c ++。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.