Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
261 views
in Technique[技术] by (71.8m points)

c++ - When should this-> be used?

I was wondering if this-> should be used both:

void SomeClass::someFunc(int powder)
{
     this->powder = powder;
}

//and
void SomeClass::someFunc(bool enabled)
{
     this->isEnabled = enabled;
}

I'm wondering if the latter is necessary to be proper or if isEnabled = enabled would suffice.

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
this->

is needed when using the member directly would be ambiguous. This could happen with template code.

Consider this:

#include <iostream>

template <class T>
class Foo
{
   public:
      Foo() {}
   protected:
      void testing() { std::cout << ":D" << std::endl; }
};

template <class T>
class Bar : public Foo<T>
{
   public:
      void subtest() { testing(); }
};

int main()
{
   Bar<int> bar;
   bar.subtest();
}

This will fail since calling testing() is dependent on a template parameter. To say that you mean the function you will have to do this->testing(); or Foo<T>::testing();

Error message:

temp.cpp: In member function ‘void Bar<T>::subtest()’:
temp.cpp:16:32: error: there are no arguments to ‘testing’ that depend on a template parameter, so a declaration of ‘testing’ must be available [-fpermissive]
temp.cpp:16:32: note: (if you use ‘-fpermissive’, G++ will accept your code, but allowing the use of an undeclared name is deprecated)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...