Error invalid use of member function did you forget the

I'm trying to wrap arduino's RF24 functions into a simpler class that I could use more intuitively in the future, so I have made a .h file: #ifndef RADIO_H #define RADIO_H #include #

I’m trying to wrap arduino’s RF24 functions into a simpler class that I could use more intuitively in the future, so I have made a .h file:

#ifndef RADIO_H
#define RADIO_H

#include <RF24.h>
#include <Arduino.h>

class Radio
{
    private:
        RF24 radio(int ce, int csn);
        int opMode;
        byte address;

    protected:
        void setReceiver();
        void setTransmitter();
    
    public:
        Radio(int ce, int csn, int mode, byte channel); 
};
 #endif

and a .cpp file:

#include "Radio.h"
#include "Parameters.h"
#include <Arduino.h>
#include <SPI.h>
#include <RF24.h>
#include <nRF24L01.h>


Radio::Radio(int ce, int csn, int mode, byte channel){
    RF24 radio(ce,csn);
  radio.begin();
  opMode = mode;
    address = channel;
    
    if(opMode == RX){
        setReceiver();
    }
    else if(opMode == TX){
        setTransmitter();
    }
}

//Protected Functions
void Radio::setReceiver(){
    //radio.openReadingPipe(0,address);
    //radio.startListening();
  
}

void Radio::setTransmitter(){
    //radio.openWritingPipe(address);
    radio.stopListening();
}

However, I’m receiving the following error and can’t figure out what’s wrong with the code:

sketchRadio.cpp: In member function ‘void Radio::setTransmitter()’:
Radio.cpp:74:2: error: invalid use of member function ‘RF24
Radio::radio(int, int)’ (did you forget the ‘()’ ?)
radio.stopListening(); ^~~~~ Radio.cpp:74:2: error: invalid use of
member function ‘RF24 Radio::radio(int, int)’ (did you forget the ‘()’
?) exit status 1 invalid use of member function ‘RF24
Radio::radio(int, int)’ (did you forget the ‘()’ ?)

can anyone help me figure out what went wrong?

—Maxim—

1 / 1 / 0

Регистрация: 28.10.2017

Сообщений: 48

1

03.07.2018, 16:24. Показов 6634. Ответов 4

Метки нет (Все метки)


Помогите пожалуйста понять где ошибка.
Компилятор выдаёт invalid use of member (did you forget ‘&’ ?) в 19 ряду.

Вот код:

C++ (Qt)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
void Game::Mixer(int ButtonNumbers[4][4])
{
    int x1=0, y1=0, x2, y2, r;
    for(int i=0; i<100; i++)
    {
        do
        {
            x2 = x1;
            y2 = y1;
            srand(time(0));
            r = 1+rand()%4;
            switch(r)
            {
            case 1: x2--; break;
            case 2: x2++; break;
            case 3: y2--; break;
            case 4: y2++; break;
            }
        } while((x2<0) || (x2>=4) || (y2<0) || (y>=4)); //invalid use of member (did you forget '&' ?)
        ButtonNumbers[x1][y1] = ButtonNumbers[x2][y2];
        x1 = x2;
        y1 = y2;
    }
}

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Модератор

Эксперт С++

12641 / 10135 / 6102

Регистрация: 18.12.2011

Сообщений: 27,170

03.07.2018, 16:55

2

Лучший ответ Сообщение было отмечено —Maxim— как решение

Решение

Цитата
Сообщение от —Maxim—
Посмотреть сообщение

(y>=4)

Может быть (y2>=4)

Кстати, а из каких соображений эта функция — член класса Game?
Она никаких данных класса не использует.
Сделайте ее или глобальной или static



1



1 / 1 / 0

Регистрация: 28.10.2017

Сообщений: 48

03.07.2018, 17:09

 [ТС]

3

Цитата
Сообщение от zss
Посмотреть сообщение

Может быть (y2>=4)

Пфф, вот я идиот, мне аж стыдно

Цитата
Сообщение от zss
Посмотреть сообщение

Кстати, а из каких соображений эта функция — член класса Game?

Я сам толком не понимаю как это работает, но так мне велел делать преподаватель (иначе программа не компелировалась). Дело в том что это ООП, и все функции я описываю как прототипы в заголовочном файле .h
Может это просто какая то особенность Qt? В общем не важно, уже всё работает . Большое спасибо вам за помощь. А я пойду проверю зрение



0



TheCalligrapher

Вездепух

Эксперт CЭксперт С++

10435 / 5704 / 1553

Регистрация: 18.10.2014

Сообщений: 14,100

03.07.2018, 17:28

4

Цитата
Сообщение от —Maxim—
Посмотреть сообщение

C++
1
2
srand(time(0));
r = 1+rand()%4;

Распространенные ошибки



1



1 / 1 / 0

Регистрация: 28.10.2017

Сообщений: 48

03.07.2018, 19:14

 [ТС]

5

TheCalligrapher, спасибо, очень помогло



0



  • Forum
  • General C++ Programming
  • invalid use of member (did you forget th

invalid use of member (did you forget the &?)

hi everyone, this is my first post, so bear with me.
this is driving me insane. im trying to write a program for Project Euler problem 4. here is the code that is giving me problems (its not complete yet)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/* A palindromic number reads the same both ways.
 * The largest palindrome made from the product
 * of two 2-digit numbers is 9009 = 91 × 99.
 *
 * Find the largest palindrome made from
 * the product of two 3-digit numbers.
 *
 */

#include <iostream>
#include <sstream>
#include <string.h>

using namespace std;

bool isPalindrome(int number)
{
    string check;
    stringstream out;
    out << number;
    check = out.str();

    for (int position = 0; position < (check.length/2); position++)
    {
        if (check.at(position) == check.at(check.length - position))
        {
            return false;
        }
    }
    return true;
}

int main()
{
    isPalindrome(1234);
    return 0;
}

and the errors are

/home/nick/Euler/Euler004/main.cpp||In function ‘bool isPalindrome(int)’:|
/home/nick/Euler/Euler004/main.cpp|23|error: invalid use of member (did you forget the ‘&’ ?)|
/home/nick/Euler/Euler004/main.cpp|25|error: invalid use of member (did you forget the ‘&’ ?)|
||=== Build finished: 2 errors, 0 warnings ===|

what exactly does this error message mean and how do i fix it?

Last edited on

haha duh. i forgot the () after both check.length lol. mods can delete this if they feel like it :P

Haha — yeah got to admit I’ve missed that myself a few times from typing to quickly :(

Topic archived. No new replies allowed.

#include <SimbleeBLE.h>


// constants won't change. They're used here to set pin numbers:

const int ButtonPlayPause = 15;
const int ButtonNext = 12;  
const int ButtonPrevious = 11;
const int OBled = 29;   
       int Playp = 1;


// variables will change:
int buttonState = 0;         // variable for reading the pushbutton status

void setup() 
{

  pinMode(ButtonPlayPause, INPUT);
  pinMode(ButtonNext, INPUT);
  pinMode(ButtonPrevious, INPUT);

  pinMode(OBled, INPUT);

  SimbleeBLE.deviceName = "GBAND";

  Serial.begin(115200);  

  SimbleeBLE.begin();

  SimbleeBLE.txPowerLevel = +4;
}

void loop() 
{ 
  buttonState = digitalRead(ButtonPlayPause);
  if (buttonState == HIGH) 
  {       
    SimbleeBLE.begin();
    SimbleeBLE.deviceName = "GBAND";
    //More code here to establish connection with android
     SimbleeBLE.sendInt = (Playp);
    digitalWrite(OBled, HIGH);
    SimbleeBLE.end();
    digitalWrite(OBled, LOW);
  } else  {  
            buttonState = digitalRead(ButtonNext);
            if (buttonState == HIGH) 
            {
              SimbleeBLE.begin();

              //More code here to establish connection with android

              digitalWrite(OBled, HIGH);
              SimbleeBLE.end();
              digitalWrite(OBled, LOW);
            } else  {  
                      buttonState = digitalRead(ButtonPrevious);
                      if (buttonState == HIGH) 
                      {
                        SimbleeBLE.begin();
                        //More code here to establish connection with android

                        digitalWrite(OBled, HIGH);
                        SimbleeBLE.end();
                        digitalWrite(OBled, LOW);
                      }
                    }
          }
    }

This is the error I keep getting:

Arduino: 1.8.5 (Windows Store 1.8.10.0) (Windows 10), Board: "Simblee"

C:UsersLestatDesktopSD PROJECR PAPERWORKSketch programssketch_mar20asketch_mar20a.ino: In function 'void loop()':

sketch_mar20a:42: error: invalid use of member function (did you forget the '()' ?)

     SimbleeBLE.sendInt = (Playp);
                        ^
exit status 1
invalid use of member function (did you forget the '()' ?)

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

Hi.
Sorry for the late response, but I’m having difficulties to find spare time. The project is not dead. You can always ask in forum: I’m having difficulties to find spare time.

You can solve the problem by removing this part:

class ByteString : public String {
public:
	ByteString(void *data, size_t len) :
		String() {
		copy(data, len);
	}

	ByteString() :
		String() {
	}

	String& copy(const void *data, unsigned int length) {
		if (!reserve(length)) {
			invalidate();
			return (*this);
		}
		len = length;
		memcpy(buffer, data, length);
		buffer[length] = 0;
		return (*this);
	}
};

// Asynchronous TCP Client to retrieve data/time
struct AsyncHTTPClient {
	AsyncClient *aClient = NULL;

	bool         initialized = false;
	String       protocol;
	String       base64Authorization;
	String       host;
	int          port;
	String       uri;
	String       request;

	ByteString   response;
	int          statusCode;
	void(*onSuccess)();
	void(*onFail)(String);

	void initialize(String url) {
		// check for : (http: or https:
		int index = url.indexOf(':');

		if (index < 0) {
			initialized = false;					// This is not a URLs
		}

		protocol = url.substring(0, index);
		DEBUGLN(protocol);
		url.remove(0, (index + 3));					// remove http:// or https://

		index = url.indexOf('/');
		String hostPart = url.substring(0, index);
		DEBUGLN(hostPart);
		url.remove(0, index);						// remove hostPart part

		// get Authorization
		index = hostPart.indexOf('@');

		if (index >= 0) {
			// auth info
			String auth = hostPart.substring(0, index);
			hostPart.remove(0, index + 1);                // remove auth part including @
			base64Authorization = base64::encode(auth);
		}

		// get port
		port = 80;								 //Default
		index = hostPart.indexOf(':');
		if (index >= 0) {
			host = hostPart.substring(0, index); // hostname
			host.remove(0, (index + 1));         // remove hostname + :
			DEBUGLN(host);
			port = host.toInt();                 // get port
			DEBUGLN(port);
		}
		else {
			host = hostPart;
			DEBUGLN(host);
		}
		uri = url;
		if (protocol != "http") {
			initialized = false;
		}

		DEBUGLN(initialized);
		request = "GET " + uri + " HTTP/1.1rnHost: " + host + "rnrn";

		DEBUGLN(request);
		initialized = true;
	}

	int getStatusCode() {
		return (statusCode);
	}

	String getBody() {
		if (statusCode == 200) {
			int bodyStart = response.indexOf("rnrn") + 4;
			return (response.substring(bodyStart));
		}
		else {
			return ("");
		}
	}

	static void clientError(void *arg, AsyncClient *client, int error) {
		DEBUGLN("Connect Error");
		AsyncHTTPClient *self = (AsyncHTTPClient *)arg;
		self->onFail("Connection error");
		self->aClient = NULL;
		delete client;
	}

	static void clientDisconnect(void *arg, AsyncClient *client) {
		DEBUGLN("Disconnected");
		AsyncHTTPClient *self = (AsyncHTTPClient *)arg;
		self->aClient = NULL;
		delete client;
	}

	static void clientData(void *arg, AsyncClient *client, void *data, size_t len) {
		DEBUGLN("Got response");

		AsyncHTTPClient *self = (AsyncHTTPClient *)arg;
		self->response = ByteString(data, len);
		String status = self->response.substring(9, 12);
		self->statusCode = atoi(status.c_str());
		DEBUGLN(status.c_str());

		if (self->statusCode == 200) {
			self->onSuccess();
		}
		else {
			self->onFail("Failed with code " + status);
		}
	}

	static void clientConnect(void *arg, AsyncClient *client) {
		DEBUGLN("Connected");

		AsyncHTTPClient *self = (AsyncHTTPClient *)arg;

		self->response.copy("", 0);
		self->statusCode = -1;

		// Clear oneError handler
		self->aClient->onError(NULL, NULL);

		// Set disconnect handler
		client->onDisconnect(clientDisconnect, self);

		client->onData(clientData, self);

		//send the request
		client->write(self->request.c_str());
	}

	void makeRequest(void(*success)(), void(*fail)(String msg)) {
		onFail = fail;

		if (!initialized) {
			fail("Not initialized");
			return;
		}

		if (aClient) {           //client already exists
			fail("Call taking forever");
			return;
		}

		aClient = new AsyncClient();

		if (!aClient) {           //could not allocate client
			fail("Out of memory");
			return;
		}

		onSuccess = success;

		aClient->onError(clientError, this);

		aClient->onConnect(clientConnect, this);

		if (!aClient->connect(host.c_str(), port)) {
			DEBUGLN("Connect Fail");
			fail("Connection failed");
			AsyncClient *client = aClient;
			aClient = NULL;
			delete client;
		}
	}
};

AsyncHTTPClient httpClient;

It’s no longer needed.

  


Сообщ.
#1

,
21.08.13, 13:57

    Junior

    *

    Рейтинг (т): нет

    Народ помогите. Пишу программу, которая должна определить все МАК и IP адрес, что-то на подобии tcpdump. Платформа Ubuntu 10.04.
    Есть программный код, который определяет МАК адреса. Решил его переделать его из С в С + +, соответственно с классом и H файлом

    ExpandedWrap disabled

      #include <pcap.h>

      #include <stdlib.h>

      #include <signal.h>

      #include <netinet/ip.h>

      #include <netinet/if_ether.h>

      #include <arpa/inet.h>

      #include <netinet/ether.h>

      #include <unistd.h>

      int child_pid = 0;

      void print_eth_addr(void *addr) {

        printf(«%sn», ether_ntoa((struct ether_addr *)addr));

        kill(child_pid, 9);

        exit(0);

      }

      void find_eth_addr(struct in_addr *search_ip, const struct pcap_pkthdr* pkthdr, const u_char *packet) {

        struct ether_header *eth_hdr = (struct ether_header *)packet;

        if (ntohs(eth_hdr->ether_type) == ETHERTYPE_IP) {

          struct ip *ip_hdr = (struct ip *)(packet + sizeof(struct ether_header));

          if (ip_hdr->ip_dst.s_addr == search_ip->s_addr)

            print_eth_addr(eth_hdr->ether_dhost);

          if (ip_hdr->ip_src.s_addr == search_ip->s_addr)

            print_eth_addr(eth_hdr->ether_shost);

        }

      }

      int main(int argc, char **argv)

      {

        char *dev, errbuf[PCAP_ERRBUF_SIZE];

        pcap_t* descr;

        bpf_u_int32 maskp, netp;

        if (argc < 2) {

          printf(«Usage: %s <ip> [interface]n», argv[0]);

          return 1;

        }

        if (argc == 2 && !(dev = pcap_lookupdev(errbuf))) {

          fprintf(stderr, «%sn», errbuf); return 1;

        } else if (argc == 3) {

          dev = argv[2];

        }

        pcap_lookupnet(dev,&netp,&maskp,errbuf);

        if (!(descr = pcap_open_live(dev, BUFSIZ, 1, -1, errbuf))) {

          printf(«pcap_open_live(): %sn», errbuf); return 1;

        }

        struct in_addr search_ip;

        if (!inet_aton(argv[1], &search_ip)) {

          fprintf(stderr, «bad ipn»); exit(1);

        }

        int pid = fork();

        if (pid == 0) {

          while (1) {

            struct sockaddr_in sin;

            sin.sin_family = PF_INET;

            inet_aton(argv[1], &sin.sin_addr);

            sin.sin_port = htons(1);

            int s = socket(PF_INET, SOCK_STREAM, 0);

            connect(s, (struct sockaddr *)&sin, sizeof(sin));

            usleep(100000);

          }

        } else {

          child_pid = pid;

          //pcap_loop(descr, -1, (pcap_handler)find_eth_addr, (void *)&search_ip);

      pcap_loop(descr, -1, (pcap_handler)find_eth_addr, (u_char *)&search_ip);

        }

        return 0;

      }

    Код рабочий, дальше идет моя интерпретация. Соответственно h и cpp.
    local_mac.h

    ExpandedWrap disabled

      #pragma once

      #ifndef BASIC_H

      #define BASIC_H

      #include <pcap.h>

      #include <stdlib.h>

      #include <signal.h>

      #include <netinet/ip.h>

      #include <netinet/if_ether.h>

      #include <arpa/inet.h>

      #include <netinet/ether.h>

      #include <unistd.h>

       int child_pid = 0;

      class LocalMacAdd

      {

          public:

          LocalMacAdd(int ARGC, char **ARGV);

          int GetAddres();

          private:

         void print_eth_addr(void *addr);

         void find_eth_addr(struct in_addr *search_ip, const struct pcap_pkthdr* pkthdr, const u_char *packet);

       char *dev, *ErrorBuffer,**argv;

       struct in_addr search_ip;

        pcap_t* descr;

        bpf_u_int32 maskp, netp;

        int argc;

      };

      #endif

    local_mac.cpp

    ExpandedWrap disabled

      #include «local_mac.h»

      #include <iostream>

      using namespace std;

      LocalMacAdd::LocalMacAdd(int  ARGC, char **ARGV)

      {

      argc = ARGC;

      argv = ARGV;

      }

      void LocalMacAdd::print_eth_addr(void *addr)

      {

          cout << »  » << ether_ntoa((struct ether_addr *)addr) << » » << endl;

        kill(child_pid, 9);

        exit(0);

      }

      void LocalMacAdd::find_eth_addr(struct in_addr *search_ip, const struct pcap_pkthdr* pkthdr, const u_char *packet)

      {

      struct ether_header *eth_hdr = (struct ether_header *)packet;

        if (ntohs(eth_hdr->ether_type) == ETHERTYPE_IP) {

          struct ip *ip_hdr = (struct ip *)(packet + sizeof(struct ether_header));

          if (ip_hdr->ip_dst.s_addr == search_ip->s_addr)

            print_eth_addr(eth_hdr->ether_dhost);

          if (ip_hdr->ip_src.s_addr == search_ip->s_addr)

            print_eth_addr(eth_hdr->ether_shost);

        }

      }

      int LocalMacAdd::GetAddres()//int argc, char **argv)

      {

      ErrorBuffer = new char[PCAP_ERRBUF_SIZE];

      if (argc < 2) {

          cout << » Usage: <ip> [interface]n» << argv[0] << endl;

          return 1;

        }

      if (argc == 2 && !(dev = pcap_lookupdev(ErrorBuffer))) {

          cerr << »  » << ErrorBuffer << »  » << endl;

          return 1;

        } else if (argc == 3) {

          dev = argv[2];

        }

      pcap_lookupnet(dev,&netp,&maskp,ErrorBuffer);

       if (!(descr = pcap_open_live(dev, BUFSIZ, 1, -1, ErrorBuffer))) {

           cout << «pcap_open_live(): n » << ErrorBuffer << endl;

           return 1;

        }

        //struct in_addr search_ip;

        if (!inet_aton(argv[1], &search_ip)) {

            cerr << «bad ipn» << endl;

            exit(1);

        }

      int pid = fork();

        if (pid == 0) {

          while (1) {

            struct sockaddr_in sin;

            sin.sin_family = PF_INET;

            inet_aton(argv[1], &sin.sin_addr);

            sin.sin_port = htons(1);

            int s = socket(PF_INET, SOCK_STREAM, 0);

            connect(s, (struct sockaddr *)&sin, sizeof(sin));

            usleep(100000);

          }

        } else {

          child_pid = pid;

         // u_char * temp =(u_char *) search_ip;

      pcap_loop(descr, -1, (pcap_handler)find_eth_addr,((u_char *) (&search_ip)) );

      //pcap_loop(descr, -1, (pcap_handler)find_eth_addr,(u_char *)&search_ip);

        }

      }

    Сама ошибка находится в строке

    ExpandedWrap disabled

      pcap_loop(descr, -1, (pcap_handler)find_eth_addr,((u_char *) (&search_ip)) );

    local_mac.cpp:69: error: invalid use of member (did you forget the ‘&’?)
    сигнатура функции

    ExpandedWrap disabled

      int pcap_loop(pcap_t *p, int cnt, pcap_handler callback, u_char *user)

    Возможно кто-то чем-то поможет :rolleyes:

    Сообщение отредактировано: pesekot — 21.08.13, 14:01

    Guru

    Qraizer
    Online



    Сообщ.
    #2

    ,
    21.08.13, 14:34

      Moderator

      *******

      Рейтинг (т): 520

      LocalMacAdd::find_eth_addr() — это не свободная функция, это метод класса, и поэтому да, указатели на них должны браться явно. Но не это главное. Взяв указатель на него, ты получишь не тип pcap_handler. Сравни:

      ExpandedWrap disabled

        typedef void (             *func_ptr  )(struct in_addr *, const struct pcap_pkthdr*, const u_char *);

        typedef void (LocalMacAdd::*member_ptr)(struct in_addr *, const struct pcap_pkthdr*, const u_char *);

      Более того, эти типы неприводимы друг к другу. Даже явный каст типа даст ошибку. И это правильно, методу нужен this, а C-коду, использующему тип pcap_handler, неоткуда его взять, он вообще не курсе, что что-то ещё нужно. Если компилятор такое пропустит, код обязательно свалится, ибо this будет мусором.


      pesekot



      Сообщ.
      #3

      ,
      21.08.13, 14:54

        Junior

        *

        Рейтинг (т): нет

        Цитата Qraizer @ 21.08.13, 14:34

        А если функцию GetAddres () объявить вне класса, и в ней инициализировать объект класса LocalMacAdd?

        Guru

        Qraizer
        Online



        Сообщ.
        #4

        ,
        21.08.13, 17:23

          Moderator

          *******

          Рейтинг (т): 520

          Что-то я смутно представляю, как это тебе поможет. Давай я набросаю идею, а ты посмотри, что из этого будет полезным.
          Обычно в случаях, когда легаси-коду требуется передать метода класса, коллбэком делают всё-таки свободную функцию. Или статический метод, их сигнатуры от this не зависят и в общем-то совместимы со свободными функциями. При этом this как-то куда-то передают на сохранение, чтобы в этой свободной функции его достать и использовать по назначению — вызвать с ним требуемый его метод. Способов много. Например, в WinAPI у подавляющего большинства коллбэков в параметрах обязательно предусмотрен некий void*, каковой самим WinAPI не используется и просто передаётся из точки API-вызова в коллбэк. Например (для большей ясности определения чуть изменены):

          ExpandedWrap disabled

            BOOL EnumWindows(WNDENUMPROC lpEnumFunc, LPARAM lParam);

            typedef BOOL (*WNDENUMPROC)(HWND hwnd, LPARAM lParam);

          Этот самый lParam и является тем самым пользовательским данным. В него можно запихать, что душе угодно, им может быть указатель на структурку с передаваемыми в коллбэк параметрами и в частности this. Я предлагаю тебе использовать что-то вроде этого. Беда в том, что в pcap_handler нет пользовательских параметров, как я погляжу. Но ничего, его можно замешать в имеющиеся. Правда, все эти касты… будь они неладны. Вот наколеночное, я его не тестил, хоть и относительно, но-таки более-менее безопасное, решение. Используется RTTI для контроля в run-time:

          ExpandedWrap disabled

            struct in_addr_proxy

            {

              struct in_addr* search_ip;

              LocalMacAdd*    it_is_this;

                       in_addr_proxy(struct in_addr* ip, LocalMacAdd* obj): search_ip(ip), it_is_this(obj) {}

              operator in_addr*     () const                                                               { return search_ip; }

              virtual ~in_addr_proxy()                                                                     {}

            };

            void find_eth_addr_proxy(struct in_addr *search_ip, const struct pcap_pkthdr* pkthdr, const u_char *packet)

            {

              in_addr_proxy *restored = (in_addr_proxy *)((char*)search_ip — offsetof(in_addr_proxy, search_ip));

              if (typeid(*restored) != typeid(in_addr_proxy)) throw std::invalid_argument(«find_eth_addr_proxy(): 1st param hasn’t the in_addr_proxy type»);

              restored->it_is_this->find_eth_addr(restored->search_ip, pkthdr, packet);

            }

            /* … */

            pcap_loop(descr, -1, find_eth_addr_proxy, (u_char*)(in_addr*)&(in_addr_proxy(&search_ip, this)));

          P.S. Могут присутствовать даже опечатки.

          Сообщение отредактировано: Qraizer — 21.08.13, 17:29


          pesekot



          Сообщ.
          #5

          ,
          21.08.13, 18:20

            Junior

            *

            Рейтинг (т): нет

            Цитата Qraizer @ 21.08.13, 17:23

            Что-то я смутно представляю, как это тебе поможет. Давай я набросаю идею, а ты посмотри, что из этого будет полезным.
            Обычно в случаях, когда легаси-коду требуется передать метода класса, коллбэком делают всё-таки свободную функцию. Или статический метод, их сигнатуры от this не зависят и в общем-то совместимы со свободными функциями. При этом this как-то куда-то передают на сохранение, чтобы в этой свободной функции его достать и использовать по назначению — вызвать с ним требуемый его метод. Способов много. Например, в WinAPI у подавляющего большинства коллбэков в параметрах обязательно предусмотрен некий void*, каковой самим WinAPI не используется и просто передаётся из точки API-вызова в коллбэк. Например (для большей ясности определения чуть изменены):

            ExpandedWrap disabled

              BOOL EnumWindows(WNDENUMPROC lpEnumFunc, LPARAM lParam);

              typedef BOOL (*WNDENUMPROC)(HWND hwnd, LPARAM lParam);

            Этот самый lParam и является тем самым пользовательским данным. В него можно запихать, что душе угодно, им может быть указатель на структурку с передаваемыми в коллбэк параметрами и в частности this. Я предлагаю тебе использовать что-то вроде этого. Беда в том, что в pcap_handler нет пользовательских параметров, как я погляжу. Но ничего, его можно замешать в имеющиеся. Правда, все эти касты… будь они неладны. Вот наколеночное, я его не тестил, хоть и относительно, но-таки более-менее безопасное, решение. Используется RTTI для контроля в run-time:

            ExpandedWrap disabled

              struct in_addr_proxy

              {

                struct in_addr* search_ip;

                LocalMacAdd*    it_is_this;

                         in_addr_proxy(struct in_addr* ip, LocalMacAdd* obj): search_ip(ip), it_is_this(obj) {}

                operator in_addr*     () const                                                               { return search_ip; }

                virtual ~in_addr_proxy()                                                                     {}

              };

              void find_eth_addr_proxy(struct in_addr *search_ip, const struct pcap_pkthdr* pkthdr, const u_char *packet)

              {

                in_addr_proxy *restored = (in_addr_proxy *)((char*)search_ip — offsetof(in_addr_proxy, search_ip));

                if (typeid(*restored) != typeid(in_addr_proxy)) throw std::invalid_argument(«find_eth_addr_proxy(): 1st param hasn’t the in_addr_proxy type»);

                restored->it_is_this->find_eth_addr(restored->search_ip, pkthdr, packet);

              }

              /* … */

              pcap_loop(descr, -1, find_eth_addr_proxy, (u_char*)(in_addr*)&(in_addr_proxy(&search_ip, this)));

            P.S. Могут присутствовать даже опечатки.

            Спасибо за ответ, но я уже просто напросто для этого решения исключил класс, WinAPI не подойдет так как платформа Ubuntu 10.04. Запустил твое решение, просто без дебага выдало следующие ошибки, возможно наследникам пригодится :)

            ExpandedWrap disabled

              root@ubuntu:/home/administrator/Desktop/projectM# g++ -o main main.cpp basic_info.cpp local_mac.cpp -lpcap

              local_mac.cpp: In function ‘void find_eth_addr_proxy(in_addr*, const pcap_pkthdr*, const u_char*)’:

              local_mac.cpp:38: warning: invalid access to non-static data member ‘in_addr_proxy::search_ip’  of NULL object

              local_mac.cpp:38: warning: (perhaps the ‘offsetof’ macro was used incorrectly)

              local_mac.cpp:40: error: ‘invalid_argument’ was not declared in this scope

              local_mac.cpp:15: error: ‘void LocalMacAdd::find_eth_addr(in_addr*, const pcap_pkthdr*, const u_char*)’ is private

              local_mac.cpp:41: error: within this context

              local_mac.cpp: In member function ‘int LocalMacAdd::GetAddres()’:

              local_mac.cpp:87: error: invalid use of member (did  you forget the ‘&’ )

            Спасибо за быстрый ответ :good:

            Guru

            Qraizer
            Online



            Сообщ.
            #6

            ,
            21.08.13, 19:29

              Moderator

              *******

              Рейтинг (т): 520

              Похоже, очередной раз идейный код был тупо использован в качестве готового решения. А подумать?
              Я ж говорил, что WinAPI тут для примера. Просто демонстрация дизайна кода, как обычно дружатся объекты с простым структурным API. Что касается остального… построчно:

              1. Это понятно. Многие реализации offsetof этим грешат. Хотя формально написать его так, чтобы не привлекать NULL-поинтеры, не проблема, авторы многих <cstddef> ленятся…
              2. …Исправить это можно, написав собственный его аналог. Это несложно.
              3. Это понятно. #include <stdexcept>. Кроме того, это ж просто обработка ошибки, которой быть не должно, ибо это означает крупную лажу в коде. Исключения в таких случаях вполне уместны, однако у тебя может быть другое мнение, обрабатывай на своё усмотрение.
              4. Ну не зря же у меня struct. Во-первых, тесно связанная с LocalMacAdd свободная функция вполне может быть и другом, …
              5. …во-вторых, статические методы я тоже упоминал.
              6. Не вижу причины. Вероятно следовало уточнить &this->search_ip.

              Сообщение отредактировано: Qraizer — 21.08.13, 19:33


              pesekot



              Сообщ.
              #7

              ,
              21.08.13, 20:41

                Junior

                *

                Рейтинг (т): нет

                Цитата Qraizer @ 21.08.13, 19:29

                Похоже, очередной раз идейный код был тупо использован в качестве готового решения. А подумать?
                Я ж говорил, что WinAPI тут для примера. Просто демонстрация дизайна кода, как обычно дружатся объекты с простым структурным API. Что касается остального… построчно:

                1. Это понятно. Многие реализации offsetof этим грешат. Хотя формально написать его так, чтобы не привлекать NULL-поинтеры, не проблема, авторы многих <cstddef> ленятся…
                2. …Исправить это можно, написав собственный его аналог. Это несложно.
                3. Это понятно. #include <stdexcept>. Кроме того, это ж просто обработка ошибки, которой быть не должно, ибо это означает крупную лажу в коде. Исключения в таких случаях вполне уместны, однако у тебя может быть другое мнение, обрабатывай на своё усмотрение.
                4. Ну не зря же у меня struct. Во-первых, тесно связанная с LocalMacAdd свободная функция вполне может быть и другом, …
                5. …во-вторых, статические методы я тоже упоминал.
                6. Не вижу причины. Вероятно следовало уточнить &this->search_ip.

                Друг, подумать всегда полезно но мне нужно завтра уже сдавать :)

                05-16-2011


                #1

                Tan Lee is offline


                Registered User


                Help with error: invalid use of member (did you forget the ‘&’ ?)

                HI. I’m new to programming. can someon help me explain this error?

                insert

                Code:

                //Jeff Chhouk
                //Package Shipping Project
                #include <iostream>
                using namespace std;
                
                class Package// declare base class
                
                
                {
                private:
                public:
                   Package(char *, char *);  //constructor
                  ~Package(); //destructor
                   virtual float calcShipcost()=0;  //zero to make abstract
                   virtual void print()=0;
                protected:   
                
                char *first, *last;  //for first and last name
                
                   int Numofitems;
                   int overnightd();
                   int insurance();
                   
                };
                
                
                Package :: Package(char *f, char *l)
                {
                first=new char[strlen(f)+1];
                strcpy(first, f);
                last= new char [strlen(l)+1];
                strcpy(last, l);
                }
                
                Package::~Package() // using destructor
                {
                  delete[] first;
                  delete[] last;
                }
                
                void Package:: print()
                { 
                   cout<< first<< "  " << last;
                }
                
                
                
                
                
                class Tshirts : public Package // declaring derived class of tshirts with base class of Package
                
                {
                
                
                
                
                public:
                   Tshirts();// constructor
                  ~Tshirts(); //destructor
                  virtual float calcShipcost();
                };
                
                float Tshirts:: calcShipcost()
                {
                
                  if(overnightd==1 && insurance==1 )//zero no and one is yes
                 return (Numofitems*2.75)+10+(.02*(Numofitems*2.75));//for yes on insuranances and yes delivery
                   
                else  if      (overnightd==1 && insurance==0)
                   return (Numofitems*2.75)+10;
                 else  if    (overnightd==0  && insurance==1)
                     return(Numofitems*2.75)+(.02*(Numofitems*2.75)) ;
                else   
                    (overnightd==0 && insurance==0)
                     return(Numofitems*2.75) ;
                      
                }
                
                Void Tshirts:: print()
                ]{
                cout<<"T shirts cost is:";
                Package::print();
                }
                
                
                
                int main
                {
                
                Tshirt tees("Joe", "Smith" 2,1,0);
                tees.print();//T shirts cost is:$15.50
                cout<<"$"<<tees.calc Shipcost()<<endl;
                
                
                system("PAUSE");// must be before return 0
                return o;
                }

                Output:
                t.cpp: In member function ‘virtual float Tshirts::calcShipcost()’:
                Line 66: error: invalid use of member (did you forget the ‘&’ ?)
                compilation terminated due to -Wfatal-errors.

                I bold the error line.


                I’m working on an assignment where I create my own container using templates. The container I am required to use is called Smaph, which takes in two pairs of numbers and does a variety of functions with them. I am only allowed to make a header file for this assignment. I’ve created a singly-linked class slink, that takes one template argument.

                Currently, I am trying to get a feel for templates and learning how to use them, so I have a very simple example I was hoping you could help me with. I have a push_back function in my singly linked list class to add to my templates. For some reason, I can’t add things to my slink because I get a compile time error that says, Invalid use of member function, (push_back), did you forget the ( )? Can someone explain to me why I am getting this error? Thank you!

                template <typename T>
                class slink {
                  private:
                    struct node {
                    T datum;
                    struct node *next;
                    };
                    node *head, *tail;
                  public:
                     slink() : head(0), tail(0) {
                    }
                
                    ~slink() {
                    clear();
                    }
                    void push_back(const T &datum) {
                    node *p = new node;
                    p->datum = datum;
                    p->next = 0;
                    if (!tail)
                        head = p;
                    else
                        tail->next = p;
                    tail = p;
                    }
                
                template <typename Tfirst, typename Tsecond>
                class Smaph {
                
                    public:
                        Smaph();
                        ~Smaph();
                        Smaph(const Tfirst a, const Tsecond b) {
                            std::pair<Tfirst, Tsecond> pair1(a, b);
                            s.push_back(pair1);
                        }
                    private:
                
                        slink<std::pair<Tfirst, Tsecond> > s();
                
                };
                
                

                And finally, my main to test my program. All I want to do right now is add these two numbers to my singly linked list through my Smaph.

                int main() {
                        Smaph<int, double> s(3, 6.3);
                }
                
                

                slink<std::pair<Tfirst, Tsecond> > s();
                
                

                This is a declaration of a function called s that takes no arguments and returns a slink<std::pair<Tfirst, Tsecond> >. When the compiler sees you do s.push_back(pair1);, it wonders what you’re trying to do to that poor function. Remove the () to make it a data member:

                slink<std::pair<Tfirst, Tsecond> > s;
                
                

                Автор Тема: Я думаю, обыденная ошибка у тех, кто работает в QtCreator  (Прочитано 2290 раз)
                Wizard

                Гость


                Ребят, подскажите, как мне избавиться от ошибки, которая не возникает у тех, кто кодит в MS VS, и у тех, кто кодит в Qt Creator она вот есть, и хрен знает, что поделать.
                Текст ошибки:
                invalid use of member function (did you forget the ‘()’ ?)
                          ui->widget->y = ui->spinBox->value();
                                              ^

                Привожу фрагмент кода, к которому относится данное сообщение:[/b]
                void MainWindow::on_spinBox_valueChanged(int)
                {
                    ui->widget->y = ui->spinBox->value();
                    ui->widget->update();
                }

                Остальное точно без ошибок, всё компилится в MS VS 2012. Я качал последний кьют на момент середины-конца сентября этого года.
                Подскажите, пожалуйста, как, не выдумывая ничего особенного, сделать что-нибудь мудрое в моей ситуации.
                Заранее спасибо!


                Записан
                Пантер

                Administrator
                Джедай : наставник для всех
                *****
                Offline Offline

                Сообщений: 5876

                Жаждущий знаний

                Просмотр профиля
                WWW


                ui->widget->y () — это метод. Читай документацию. Если нужно изменить позицию, нужно юзать move.
                Да, Креатор тут никаким боком.


                Записан

                1. Qt — Qt Development Frameworks; QT — QuickTime
                2. Не используйте в исходниках символы кириллицы!!!
                3. Пользуйтесь тегом code при оформлении сообщений.

                Понравилась статья? Поделить с друзьями:
              • Error invalid use of incomplete type
              • Error invalid url unable to find install package
              • Error invalid type argument of unary have int
              • Error invalid type argument of unary have float
              • Error invalid transaction termination