Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
288 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 Answer

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...