C++ 什么是非静态成员函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7600346/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is a nonstatic member function?
提问by SirYakalot
I am being told that I can't use the 'this' keyword in a class function. I'm coming from c# and i'm used to this working, but the compiler tells me that it can only be used within nonstatic member functions.
有人告诉我,我不能在类函数中使用“this”关键字。我来自 c# 并且习惯了这种工作,但是编译器告诉我它只能在非静态成员函数中使用。
D3DXVECTOR3 position;
void Position(D3DXVECTOR3 position)
{
this.position = position;
}
回答by Mark B
In C++ you need to qualify your Position
function with the class name:
在 C++ 中,您需要Position
使用类名来限定您的函数:
void YourClassNameHere::Position(D3DXVECTOR3 position)
void YourClassNameHere::Position(D3DXVECTOR3 position)
Also from @Pubby8's answer this
is a pointer, not a reference so you need to use this->position
instead (or consider using parameter names that don't shadow class members - I like using trailing _
on my class members).
同样来自@Pubby8 的答案this
是一个指针,而不是一个引用,所以你需要使用它this->position
(或者考虑使用不影响类成员的参数名称 - 我喜欢_
在我的类成员上使用尾随)。
Also, C++ doesn't pass by reference by default so if D3DXVECTOR3
is a complicated type you'll be copying a lot of data around. Consider passing it as const D3DXVECTOR3& position
instead.
此外,C++ 默认不通过引用传递,因此如果D3DXVECTOR3
是复杂类型,您将复制大量数据。考虑将其作为const D3DXVECTOR3& position
替代。
回答by Pubby
this is a pointercontaining the address of the object.
这是一个包含对象地址的指针。
D3DXVECTOR3 position;
void YourClassNameHere::Position(D3DXVECTOR3 position)
{
this->position = position;
}
Should work.
应该管用。
D3DXVECTOR3 position;
void YourClassNameHere::Position(D3DXVECTOR3 position)
{
(*this).position = position;
}
Should also work.
也应该工作。
回答by Useless
Not only is Position
a free function (not associated with a class) the way you wrote it, but this
is also a pointer, not a reference.
Position
自由函数(不与类相关联)不仅是您编写它的方式,而且this
还是一个指针,而不是一个引用。
D3DXVECTOR3 position;
void ClassName::Position(D3DXVECTOR3 position)
{
this->position = position;
}
or, if that's supposed to be a constructor,
或者,如果这应该是一个构造函数,
ClassName::ClassName(D3DXVECTOR3 p) : position(p)
{
}