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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 17:12:37  来源:igfitidea点击:

What is a nonstatic member function?

c++methodsmembernon-static

提问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 Positionfunction with the class name:

在 C++ 中,您需要Position使用类名来限定您的函数:

void YourClassNameHere::Position(D3DXVECTOR3 position)

void YourClassNameHere::Position(D3DXVECTOR3 position)

Also from @Pubby8's answer thisis a pointer, not a reference so you need to use this->positioninstead (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 D3DXVECTOR3is a complicated type you'll be copying a lot of data around. Consider passing it as const D3DXVECTOR3& positioninstead.

此外,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 Positiona free function (not associated with a class) the way you wrote it, but thisis 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)
{
}