开发者

What is a nonstatic member function?

开发者 https://www.devze.com 2023-04-09 03:35 出处:网络
I am being told that I can\'t use the \'this\' keyword in a class function. I\'m coming from c# a开发者_StackOverflow社区nd i\'m used to this working, but the compiler tells me that it can only be use

I am being told that I can't use the 'this' keyword in a class function. I'm coming from c# a开发者_StackOverflow社区nd i'm used to this working, but the compiler tells me that it can only be used within nonstatic member functions.

D3DXVECTOR3 position;

void Position(D3DXVECTOR3 position)
{
    this.position = position;
}


this is a pointer containing 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.


In C++ you need to qualify your Position function with the class name:

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).

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.


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.

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)
{
}
0

精彩评论

暂无评论...
验证码 换一张
取 消