简体   繁体   中英

c++17 error message: “reference to non-static member function must be called” when using a macro on a vector

I'm learning c++ and was playing around with macros. I tried defining push_back as pub, and it gave me this error:

error: reference to non-static member function must be called
  vect.pub(1);

Here's my code:

#include <vector>

using namespace std;
typedef vector<int> vi;
#define pub push_back;

int main(){
  vi vect;
  vect.pub(1);
}

When I didn't use the #define and just wrote push_back , there was no error messages.

What exactly changed when I used the macro?

You should not put ';' for macro.

 #include <vector>

 using namespace std;
 typedef vector<int> vi;
 #define pub push_back

 int main(){
   vi vect;
   vect.pub(1);
 }
#define pub push_back;

//...

vect.pub(1);

This expands to the following, which is invalid syntax due to the extra ;.

vect.push_back;(1);

So drop the ; and #define pub push_back .

I'm learning c++ and was playing around with macros.

Stop. push_back is at most 6 extra keystrokes. Code is meant to be read by humans. You can't find pub in documentation, but you can find push_back .

Similarly using namespace std; is a terrible habit. There are loads of names that you don't realise you've just imported into the global namespace there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM