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 Метки нет (Все метки)
Помогите пожалуйста понять где ошибка. Вот код:
__________________
0 |
Модератор 12641 / 10135 / 6102 Регистрация: 18.12.2011 Сообщений: 27,170 |
|
03.07.2018, 16:55 |
2 |
Сообщение было отмечено —Maxim— как решение Решение
(y>=4) Может быть (y2>=4) Кстати, а из каких соображений эта функция — член класса Game?
1 |
1 / 1 / 0 Регистрация: 28.10.2017 Сообщений: 48 |
|
03.07.2018, 17:09 [ТС] |
3 |
Может быть (y2>=4) Пфф, вот я идиот, мне аж стыдно
Кстати, а из каких соображений эта функция — член класса Game? Я сам толком не понимаю как это работает, но так мне велел делать преподаватель (иначе программа не компелировалась). Дело в том что это ООП, и все функции я описываю как прототипы в заголовочном файле .h
0 |
TheCalligrapher Вездепух 10435 / 5704 / 1553 Регистрация: 18.10.2014 Сообщений: 14,100 |
||||
03.07.2018, 17:28 |
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)
|
|
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
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.
|
|
Junior Рейтинг (т): нет |
Народ помогите. Пишу программу, которая должна определить все МАК и IP адрес, что-то на подобии tcpdump. Платформа Ubuntu 10.04.
#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.
#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
#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); } } Сама ошибка находится в строке
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 ‘&’?)
int pcap_loop(pcap_t *p, int cnt, pcap_handler callback, u_char *user) Возможно кто-то чем-то поможет Сообщение отредактировано: pesekot — 21.08.13, 14:01 |
QraizerOnline |
|
Moderator Рейтинг (т): 520 |
LocalMacAdd::find_eth_addr() — это не свободная функция, это метод класса, и поэтому да, указатели на них должны браться явно. Но не это главное. Взяв указатель на него, ты получишь не тип pcap_handler. Сравни:
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 |
|
Junior Рейтинг (т): нет |
Цитата Qraizer @ 21.08.13, 14:34 А если функцию GetAddres () объявить вне класса, и в ней инициализировать объект класса LocalMacAdd? |
QraizerOnline |
|
Moderator Рейтинг (т): 520 |
Что-то я смутно представляю, как это тебе поможет. Давай я набросаю идею, а ты посмотри, что из этого будет полезным.
BOOL EnumWindows(WNDENUMPROC lpEnumFunc, LPARAM lParam); typedef BOOL (*WNDENUMPROC)(HWND hwnd, LPARAM lParam); Этот самый lParam и является тем самым пользовательским данным. В него можно запихать, что душе угодно, им может быть указатель на структурку с передаваемыми в коллбэк параметрами и в частности this. Я предлагаю тебе использовать что-то вроде этого. Беда в том, что в pcap_handler нет пользовательских параметров, как я погляжу. Но ничего, его можно замешать в имеющиеся. Правда, все эти касты… будь они неладны. Вот наколеночное, я его не тестил, хоть и относительно, но-таки более-менее безопасное, решение. Используется RTTI для контроля в run-time:
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 |
|
Junior Рейтинг (т): нет |
Цитата Qraizer @ 21.08.13, 17:23 Что-то я смутно представляю, как это тебе поможет. Давай я набросаю идею, а ты посмотри, что из этого будет полезным.
BOOL EnumWindows(WNDENUMPROC lpEnumFunc, LPARAM lParam); typedef BOOL (*WNDENUMPROC)(HWND hwnd, LPARAM lParam); Этот самый lParam и является тем самым пользовательским данным. В него можно запихать, что душе угодно, им может быть указатель на структурку с передаваемыми в коллбэк параметрами и в частности this. Я предлагаю тебе использовать что-то вроде этого. Беда в том, что в pcap_handler нет пользовательских параметров, как я погляжу. Но ничего, его можно замешать в имеющиеся. Правда, все эти касты… будь они неладны. Вот наколеночное, я его не тестил, хоть и относительно, но-таки более-менее безопасное, решение. Используется RTTI для контроля в run-time:
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. Запустил твое решение, просто без дебага выдало следующие ошибки, возможно наследникам пригодится
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 ‘&’ ) Спасибо за быстрый ответ |
QraizerOnline |
|
Moderator Рейтинг (т): 520 |
Похоже, очередной раз идейный код был тупо использован в качестве готового решения. А подумать?
Сообщение отредактировано: Qraizer — 21.08.13, 19:33 |
pesekot |
|
Junior Рейтинг (т): нет |
Цитата Qraizer @ 21.08.13, 19:29 Похоже, очередной раз идейный код был тупо использован в качестве готового решения. А подумать?
Друг, подумать всегда полезно но мне нужно завтра уже сдавать |
05-16-2011
#1
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 раз) |
|
||||||
|
||||||