accessing a static variable in C++ - c++

I'm using Qt Creator to try and create a basic calculator app. I was trying to test out the first few methods and had to write one in order to make the rest of the coding easier, however, that method isn't compiling. I'm trying to access a static variable that holds the current value of the Calculator screen, but it keeps giving me:
C:\Users\****\Documents\Qt Projects\SimpleCalculator\calculator.cpp:15: error: C2248: 'Calculator::currVal' : cannot access private member declared in class 'Calculator'
Here is the Calculator.cpp
#include "calculator.h"
#include <QLCDNumber>
Calculator::Calculator(QWidget *parent) :
QWidget(parent), ui(new Ui::Calculator)
{
ans = 0;
currVal = 0;
setupUi(this);
}
//problem method
QString getNewVal(qint64 nextDig)
{
//--------------------------------------------
long long int val = Calculator::currVal;//this is where I am trying to access the variable
//--------------------------------------------
if(nextDig==0)
{
if(val > 0)
{
QString str = QString::number(val);
str.append("0");
return str;
}
else
{
return "0";
}
}
else if(nextDig==1)
{
QString str = QString::number(val);
str.append("1");
return str;
}
return NULL;
}
void Calculator::on_Zero_clicked()
{
ui->Display->display(getNewVal(0));
currVal = ui->Display->intValue();
}
void Calculator::on_One_clicked()
{
}
Here is the header file:
#ifndef CALCULATOR_H
#define CALCULATOR_H
#include "ui_calculator.h"
class Calculator : public QWidget, private Ui::Calculator
{
Q_OBJECT
public:
Calculator(QWidget *parent = 0);
private slots:
void on_Zero_clicked();
void on_One_clicked();
private:
Ui::Calculator *ui;
QString getNewVal(quint64);
static long long int ans;
static long long int currVal;
};
long long int Calculator::ans = 0;
long long int Calculator::currVal = 0;
#endif
// CALCULATOR_H

Calculator::currVal;//this is where I am trying to access the variable
Won't work because the value is declared private (as indicated by the warning) in your header:
private:
Ui::Calculator *ui;
QString getNewVal(quint64);
static long long int ans;
**static long long int currVal;**
and your function:
QString getNewVal(qint64 nextDig)
is not part of the class.

This
static long long int currVal;
is private!
try:
public:
static long long int currVal;
or create a getter method for that.
also you can make the getNewVal a friend function of your class:
public:
friend QString ::getNewVal(qint64 nextDig);

You need to specify that getNewVal belongs to Calculator
QString Calculator::getNewVal(quint64 nextDig)
// ^^^^^^^^^^ ^
// This was missing |
// |
// Add 'u' above to match the declaration
Otherwise, C++ thinks that this is a free-standing function (despite the fact that you have declared a member function with the same name inside Calculator).
You also need to move the two definitions
long long int Calculator::ans = 0;
long long int Calculator::currVal = 0;
from the header file to the implementation file.

Related

Variable or field declared void C++

I am making a school assignment, but I am getting a strange error. I have tried to google it, but nothing helped.
So I have a file called main.cpp. Within this file I have some includes and code.
This:
#include <iostream>
#include <stdexcept>
#include <string>
using namespace std;
#include "RentalAdministration.h"
#include "Limousine.h"
#include "Sedan.h"
void addTestDataToAdministration(RentalAdministration* administration)
{
string licencePlates[] = {"SD-001", "SD-002", "SD-003", "SD-004", "LM-001", "LM-002"};
for (int i = 0; i < 4; i++)
{
Car* sedan = new Sedan("BMW", "535d", 2012 + i, licencePlates[i], false);
administration->Add(sedan);
}
for (int i = 4; i < 6; i++)
{
Car* limousine = new Limousine("Rolls Roys", "Phantom Extended Wheelbase", 2015, licencePlates[i], true);
administration->Add(limousine);
}
}
int main( void )
{
RentalAdministration administration;
addTestDataToAdministration(&administration);
}
So the compiler tells me that the variable: "RentalAdministration administration" does not exist.
So if we have look in my rentaladministration header. We see this:
#ifndef RENTALADMINISTRATION_H
#define RENTALADMINISTRATION_H
#include <vector>
#include "car.h"
class RentalAdministration
{
private:
std::vector<Car*> Cars;
Car* FindCar(std::string licencePlate);
Car* FindCarWithException(std::string licencePlate);
public:
std::vector<Car*> GetCars() const {return Cars;}
bool Add(Car* car);
bool RentCar(std::string licencePlate);
double ReturnCar(std::string licencePlate, int kilometers);
void CleanCar(std::string licencePlate);
RentalAdministration();
~RentalAdministration();
};
#endif
This is the exact error:
src/main.cpp:18:34: error: variable or field ‘addTestDataToAdministration’ declared void
void addTestDataToAdministration(RentalAdministration* administration)
^
src/main.cpp:18:34: error: ‘RentalAdministration’ was not declared in this scope
src/main.cpp:18:56: error: ‘administration’ was not declared in this scope
void addTestDataToAdministration(RentalAdministration* administration)
Help will be appreciated!
Edit:
I am getting warnings in sublime for the Sedan and Limousine headers. Something that has to do with some static constants. I think it was called a GNU extension. Maybe it has something to do with it.
Even when I comment the call of that function out. I get the same error.
I am calling that function nowhere else.
Some people say that the cause might be in these headers:
#ifndef LIMOUSINE_H
#define LIMOUSINE_H
#include "Car.h"
//c
class Limousine : public Car
{
private:
bool needsCleaning;
bool hasMiniBar;
static const double priceperkm = 2.5;
public:
double Return(int kilometers);
void Clean();
bool GetHasMiniBar() const { return hasMiniBar;}
void SetHasMiniBar(bool value) {hasMiniBar = value;}
Limousine(std::string manufacturer, std::string model, int buildYear, std::string licencePlate, bool hasminiBar);
~Limousine();
};
#endif
2:
#ifndef SEDAN_H
#define SEDAN_H
#include "Car.h"
//c
class Sedan : public Car
{
private:
int lastCleanedAtKm;
bool hasTowBar;
bool needsCleaning;
static const double priceperKm = 0.29;
public:
void Clean();
int GetLastCleanedAtKm() const {return lastCleanedAtKm;}
void SetLastCleanedAtKm(bool value){ lastCleanedAtKm = value;}
bool GetHasTowBar() const {return hasTowBar;}
void SetHasTowBar(bool value) {hasTowBar = value;}
bool GetNeedsCleaning() const {return needsCleaning;}
void SetNeedsCleaning(bool value){needsCleaning = value;}
Sedan(std::string manufacturer, std::string model, int buildYear, std::string licencePlate, bool hastowBar);
~Sedan();
};
#endif
class Limousine : public Car
{
private:
static const double priceperkm = 2.5;
...
}
Remove the static and declare the member simply as const double, example:
class Limousine : public Car
{
private:
const double priceperkm = 2.5;
...
}
The error message ‘RentalAdministration’ was not declared in this scope indicates that the right header file for RentalAdministration was not included. Check the file names to make sure class declaration for RentalAdministration is in the right file.
Restarting the terminal has somehow solved this error. I got another error this time, which I solved already. I missed the destructor. It stood in the header file, but not in the cpp file.
Buggy terminals...

TeamSpeak SDK in Qt

I'm trying to use the TeamSpeak SDK for a personal project in Qt, when I use this code in the main it works fine
It compiles without problem. The problem is when I use it in Qt Mainwindow:
Mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <teamspeak/public_definitions.h>
#include <teamspeak/public_errors.h>
#include <teamspeak/serverlib_publicdefinitions.h>
#include <teamspeak/serverlib.h>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private:
Ui::MainWindow *ui;
void onClientConnected(uint64 serverID, anyID clientID, uint64 channelID, unsigned int* removeClientError);
ServerLibFunctions funcs; // it's a struct that have pointer fucntions
};
#endif // MAINWINDOW_H
Mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
funcs.onClientConnected = onClientConnected; // error here
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::onClientConnected(uint64 serverID, anyID clientID, uint64 channelID, unsigned int* removeClientError) {
char* clientName;
unsigned int error;
/* Query client nickname */
if ((error = ts3server_getClientVariableAsString(serverID, clientID, CLIENT_NICKNAME, &clientName)) != ERROR_ok) {
char* errormsg;
if (ts3server_getGlobalErrorMessage(error, &errormsg) == ERROR_ok) {
printf("Error querying client nickname: %s\n", errormsg);
ts3server_freeMemory(errormsg);
}
return;
}
printf("Client '%s' joined channel %llu on virtual server %llu\n", clientName, (unsigned long long) channelID, (unsigned long long)serverID);
/* Example: Kick clients with nickname "BlockMe from server */
if (!strcmp(clientName, "BlockMe")) {
printf("Blocking bad client!\n");
*removeClientError = ERROR_client_not_logged_in; /* Give a reason */
}
}
I've commented on the line I got the error in Mainwindow.cpp
and the error:
cannot convert 'MainWindow::onClientConnected' from type 'void (MainWindow::)(uint64, anyID, uint64, unsigned int*) {aka void (MainWindow::)(long long unsigned int, short unsigned int, long long unsigned int, unsigned int*)}' to type 'void ()(uint64, anyID, uint64, unsigned int) {aka void ()(long long unsigned int, short unsigned int, long long unsigned int, unsigned int)}'
funcs.onClientConnected = onClientConnected;
^
I am using Windows 10 Mingw compiler Qt 5.6.1
how can i use this call back fucntion in oop c++
I solve my problem to use TeamSpeak in Qt I initialize the server in the main.cpp and assign all call back functions in the struct and now I can use any function of the server in the main window for example if I want to show the channels in a text edit i use the function of it in any c++ class or Qt Dialog and I can call it without problems
the code of the main.cpp
// put the fucntion of the call back here
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
char *version;
short abort = 0;
uint64 serverID;
unsigned int error;
int unknownInput = 0;
uint64* ids;
int i;
struct ServerLibFunctions funcs;
/* Initialize all callbacks with NULL */
memset(&funcs, 0, sizeof(struct ServerLibFunctions));
funcs.onClientConnected = onClientConnected;
funcs.onClientDisconnected = onClientDisconnected;
funcs.onClientMoved = onClientMoved;
funcs.onChannelCreated = onChannelCreated;
funcs.onChannelEdited = onChannelEdited;
funcs.onChannelDeleted = onChannelDeleted;
funcs.onServerTextMessageEvent = onServerTextMessageEvent;
funcs.onChannelTextMessageEvent = onChannelTextMessageEvent;
funcs.onUserLoggingMessageEvent = onUserLoggingMessageEvent;
funcs.onClientStartTalkingEvent = onClientStartTalkingEvent;
funcs.onClientStopTalkingEvent = onClientStopTalkingEvent;
funcs.onAccountingErrorEvent = onAccountingErrorEvent;
funcs.onCustomPacketEncryptEvent = nullptr;
funcs.onCustomPacketDecryptEvent = nullptr;
if((error = ts3server_initServerLib(&funcs, LogType_FILE | LogType_CONSOLE | LogType_USERLOGGING, NULL)) != ERROR_ok) {
char* errormsg;
if(ts3server_getGlobalErrorMessage(error, &errormsg) == ERROR_ok) {
printf("Error initialzing serverlib: %s\n", errormsg);
ts3server_freeMemory(errormsg);
}
return 1;
}
MainWindow w;
w.show();
return a.exec();
// use any function to edit server in any c++ class as show chan add chancel and so on
}
use all function to edit the server in any c++ class it will work and i think we don't need to initialize the server more than once in main and we don't need to but it in class and if I want to make a VoIP using Qt GUI we need only the server edit function if there's a better answer please post it Thanks
Edit
another solution is to initialize the struct with the call back functions in main and pass it in Mainwindow or any c++ class in the constructor and use it to initialize server lib of TeamSpeak
Your issue can be simulated with below simple code.
Based on my understanding the function you are trying to assign is a class specific member. So the compiler considers it as a signature mismatch when you are trying to assign.
You may need to write the required functionality in a non class member and then assign. (unless there is a way to allow this assignment).
Make the structure with function inputs as a friend of your functional class as shown below.
#include <iostream>
// common namespace
using namespace std;
//Structure with function pointers.
struct funcPtrStruct
{
public:
void (*func)(int a, float b);
};
//The non member function that address your functionality
void testFuncOne(int a ,float b)
{
//Do something
}
//Class implementation
class Test
{
public:
Test()
{
funcPtrStruct funPtrSt;
//func = &testFunc; //Here the error is shown " a value of type .....can not convert......"
funPtrSt.func = &testFuncOne; //This is working but it is not a class memeber.
}
private:
friend struct funcPtrStruct; //Make the structure of function pointers as your friend.
};
int main() {
return 0;
}

Declaring a Class C++

I am struggling knowing how to create a class. I want to create a "Player" class and all I want to do is pass in the name while I'll have the other variables start at 0 until they are updated when a game is run (later in the program)
Player::Player(string name_in)
{
name = name_in;
int numOfWins = 0;
int numOfLoses = 0;
int numOfDraws = 0;
int totalMatches = 0;
}
Right now there are lots of errors around numOfWins, numOfLoses, numOfDraws and totalMatches. What can I do to fix this?
Perhaps the error is in your int ... part of assignments, which essentially creates a new local variable in a constructor.
Try this version:
#include <string>
using namespace std;
class Player
{
string name;
int numOfWins;
int numOfLoses;
int numOfDraws;
int totalMatches;
public:
Player(string name_in)
{
name = name_in;
numOfWins = 0;
numOfLoses = 0;
numOfDraws = 0;
totalMatches = 0;
}
};
You should declare other instance variables in the class declaration, rather than declaring them as locals (which is completely useless).
// This part goes in the header
class Player {
string name;
int numOfWins;
int numOfLoses;
int numOfDraws;
int totalMatches;
public:
Player(string name_in);
};
Now in the constructor you could use initialization lists:
// This part goes into the CPP file
Player::Player(string name_in)
// Initialization list precedes the body of the constructor
: name(name_in), numOfWins(0), numOfLoses(0), numOfDraws(0), totalMatches(0) {
// In this case, the body of the constructor is empty;
// there are no local variable declarations here.
}
Kinda vague, but I'll take a crack at it. You Probably want:
class Player{
string name;
int numOfWins;
int numOfLosses;
int numOfDraws;
int totalMatches;
Player(string name_in)
};
Player::Player(string name_in){
name = name_in;
numOfWins = 0;
numOfLosses = 0;
numOfDraws = 0;
totalMatches = 0;
}
Haven't used C++ in a while, so this may be faulty.
The errors you get, at least from the snippet you posted are caused for you can't declare variables in constructor - you declare them in class body and initialize in constructor or using another function.
#include <string>
class Player {
public:
Player( std::string const& name_in) : name( name_in),
numOfWins(), numOfLoses(),
numOfDraws(), totalMatches()
{} // constructor
// will initialize variables
// numOfWins() means default
// initialization of an integer
private:
std::string name;
int numOfWins;
int numOfLoses;
int numOfDraws;
int totalMatches;
};
usage:
int main() {
Player( "player_one");
return 0;
}

C++ Using a class from a header within a class

I'm having a bit of trouble with classes used within classes, from header files.
I have a class time in time.h:
#ifndef TIME_H
#define TIME_H
#include <iostream>
using namespace std;
class Time
{
private:
int hour, minute, second;
public:
Time();
~Time();
Time(int h, int m, int s);
int getHour();
int getMinute();
int getSecond();
void setHour(int hour);
void setMinute(int minute);
void setSecond(int second);
Time getTimeFromUser(Time b);
bool validTime(Time a);
void print24Hour(Time a);
void print12Hour(Time b);
};
#endif
Schedule.h
#ifndef SCHEDULE_H
#define SCHEDULE_H
#include <iostream>
#include "time.h"
using namespace std;
class Class
{
private:
string name;
int credits;
bool majorRequirement;
double avgGrade;
string days;
Time startTime;
Time endTime;
public:
Class();
~Class();
Class(string namae, int cred, bool majorReq, double avg, string day);
//Mutate
void setName(string h);
void setCredits(int c);
void setMajorRequirement(bool set);
void setAvgGrade(double g);
void setDays(string d);
void getStartTimeFromUser(Time b);
void getEndTimeFromUser(Time e);
// Access
string getName();
int getCredits();
bool getMajorRequirement();
double getAvgGrade();
string getDays();
Time& getStartTime();
Time& getEndTime();
};
#endif
Schedule.cpp:
Class::Class()
{
string name = "";
int credits = 0;
bool majorRequirement = false;
double avgGrade = 0.0;
string days = "";
}
Time::Time()
{
int hour = 0;
int minute = 0;
int second = 0;
}
Class::Class(string namae, int cred, bool majorReq, double avg, string day)
{
name = namae;
credits = cred;
majorRequirement = majorReq;
avgGrade = avg;
days = day;
}
Time::Time(int h, int m, int s)
{
second = s;
minute = m;
hour = h;
}
Time getTimeFromUser(Time b)
{
string time = "";
string hourS, minuteS, secondS = new string();
getline(cin,time);
hourS = time.substr(0,2);
minuteS = time.substr(3,2);
secondS = time.substr(6,2);
b.hour = atoi(hourS.c_str());
b.minute = atoi(minuteS.c_str());
b.second = atoi(secondS.c_str());
return b;
}
void getStartTimeFromUser(Time b)
{
startTime = getTimeFromUser(b);
}
void getEndTimeFromUser(Time e)
{
endTime = getTimeFromUser(e);
}
Other Mutators and Accessors here.
Main is long. Here is the severely condensed version:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <iomanip>
#include "time.h"
#include "schedule.h"
using namespace std;
int main()
{
// Expecting that variables are properly declared
Class * klass = new Class[classcount];
cout << "Enter the start time for the class (format is HH:MM:SS): ";
klass[i].getStartTimeFromUser(classB);
cout << "Enter the end time for the class (format is HH:MM:SS): ";
klass[i].getEndTimeFromUser(classE);
for(int i = 0; i < classcount; i++)
{
// Data collected via getline and changed through mutators/accessors
// Problems arise when working with Time
klass[i].getStartTime().print24hour();
}
}
I get quite a few "hour, second, minute, etc." are private errors, I'm guessing I'm doing something simple in a rather wrong way. Please help.
I get a lot of this:
time.h:10:7: error: ‘int Time::hour’ is private
schedule.cpp:146:4: error: within this context
time.h:10:13: error: ‘int Time::minute’ is private
schedule.cpp:147:4: error: within this context
time.h:10:21: error: ‘int Time::second’ is private
schedule.cpp:148:4: error: within this context
schedule.cpp: In function ‘void getStartTimeFromUser(Time)’:
schedule.cpp:155:16: error: ‘setStartTime’ was not declared in this scope
schedule.cpp: In function ‘void getEndTimeFromUser(Time)’:
schedule.cpp:160:2: error: ‘endTime’ was not declared in this scope
time.h: In function ‘bool validTime(Time)’:
There are several errors in your code:
I assume class in your main() function represents an array of
Class; but this is illegal, since class is a C++ keyword.
You are trying to access a private member of a Class object
(class[i].startTime). This is illegal again. You would need a
public accessor to that data member:
You are calling a function that does not exist (print24()). If you
intended to call print24hour(), this function takes no parameters.
Putting it all together, you need to do three things:
Add an accessor for startTime in Class:
class Class
{
//...
public:
Time GetStartTime() {return startTime;}
};
Use a legal name for your array and use std::vector or std::array:
std::vector<Class> classArray;
// OR:
std::array<Class, SIZE> classArray;
Call the right methods correctly:
classArray[i].GetStartTime().print24hour();
I you want to access class[i].startTime.print24(getStartTime()) from main you need to make startTimepublic.
If this is good style is a different question.
You are trying to access the private members of a class using the object directly.
Please read about public and private access specifiers here.
class Class
{
private:
Time startTime;
public:
const Time & getStartTime(){
return startTime;
}
};
int main()
{
Class c;
c.getStartTime().print24Hour();
}
You want either that, or make startTime public.
Note the const; if you don't want the returned reference to be const, then make startTime public right now. You may think that making it private improves encapsulation; and yes, it does, as long as you don't provide read-write access to the variable, which happens if you don't mark the member function return type const.
If your printing function isn't marked const, then your const-correctness doesn't exist. If using const reference as return type here, then you have some things to fix.
Related reading: Pseudo-Classes and Quasi-Classes.

error LNK1169: one or more multiply defined symbols found

I have 3 files:
SilverLines.h
SilverLines.cpp
main.cpp
At SilverLines.cpp I have:
#include "SilverLines.h."
When I don't do:
#include "SilverLines.h"
at the main.cpp, everything is just fine. The project compiles.
But when I do:
#include "SilverLines.h"
in the main.cpp (Which i need to do), i get these 2 errors:
What's the problem?
> edit:
As you requested, this is the entire *.h code:
#ifndef SILVER_H
#define SILVER_H
#include <iostream>
#include <algorithm>
#include <iterator>
#include <vector>
#include <string>
#include <map>
using namespace std;
typedef unsigned short int u_s_int;
map<string /*phone*/,string /*company*/> companies; // a map of a phone number and its company
string findCompany(const string& phoneNum); //Given a phone number, the function returns the right company
//The Abstract Client Class:
class AbsClient //Abstract Client Class
{
protected:
//string phone_number;
int counter; //CALL DURATION TO BE CHARGED
double charge;
public:
string phone_number; //MOVE TO PROTECTED LATER
void setCharge(double ch) {charge=ch;}
void setCoutner(int count) {counter=count;}
AbsClient(string ph_num): phone_number(ph_num),counter(0), charge(0.0) {} //c'tor that must be given a phone#.
//Initializes the counter and the charge to 0.
virtual void registerCall(string /*phone#*/, int /*minutes*/) = 0; //make a call and charge the customer
void printReport(string /*phone#*/) const; //prints a minutes report
};
//The Temporary Client Class:
class TempClient : public AbsClient //TempClient class (NO DISCOUNT!) 2.3 NIS PER MINUTE, inherits from ABS
{
private:
string company;
public:
//string company;
TempClient(string ph_num, string cmp_name): AbsClient(ph_num), company(cmp_name) {}
virtual void registerCall(string /*phone#*/, int /*minutes*/); //make a call and charge the customer
//virtual void printReport(string phone) const {cout << "the number of minutes: " << this->counter << endl;}
};
//The REgistered Client Class:
class RegisteredClient : public AbsClient //RegisteredClient, 10% DISCOUNT! , inherits from ABS
{
protected:
string name;
string id;
long account; //ACCOUNT NUMBER
private:
static const int discount = 10; //STATIC DISCOUNT OF 10% FOR ALL Registered Clients
public:
RegisteredClient(string ph_num, string n, string i, long acc_num): AbsClient(ph_num), name(n) , id(i) , account(acc_num) {}
virtual void registerCall(string /*phone#*/, int /*minutes*/); //make a call and charge the customer
//virtual void printReport(string /*phone#*/) const {cout << "the number of minutes: " << this->counter << endl;}
};
//The VIP Client Class
class VIPClient : public RegisteredClient //VIP Client! X% DISCOUNT! also, inherits from RegisteredClient
{
private: //protected?
int discount; //A SPECIAL INDIVIDUAL DISCOUTN FOR VIP Clients
public:
VIPClient(string ph_num, string n, string i, long acc_num, int X): RegisteredClient(ph_num,n,i,acc_num), discount(X) {}
virtual void registerCall(string /*phone#*/, int /*minutes*/); //make a call and charge the customer
//virtual void printReport(string /*phone#*/) const {cout << "the number of minutes: " << this->counter << endl;}
};
//The SilverLines (the company) class
class SilverLines // The Company Class
{
protected:
vector<AbsClient*> clients;
vector<string> address_book; //DELETE
public:
//static vector<AbsClient*> clients;
//SilverLines();
void addNewClient(string /*phone#*/);
void addNewClient(string /*phone#*/, string /*name*/ , string /*id*/ , u_s_int /*importance lvl*/ , long /*account#*/);
void registerCall(string /*phone#*/ , int /*call duration*/);
void resetCustomer(string /*phone#*/); //given a phone#, clear the appropriate customer's data ('charge' and 'counter')
void printReport(string /*phone#*/) const;
~SilverLines(){
vector<AbsClient*>::iterator it;
for(it = clients.begin(); it != clients.end(); ++it)
delete(*it);
}
};
#endif
paercebal's Answer:
Your code has multiple issues (the
using namespace std;
for one), but the one failing the compilation is the declaration of a global variable in a header:
map<string /*phone*/,string /*company*/> companies;
I'm quite sure most of your sources (main.cpp and SilverLines.cpp, at least) include this header.
You should define your global object in one source file:
// SilverLines.h
extern map<string /*phone*/,string /*company*/> companies;
and then declare it (as extern) in the header:
// global.cpp
extern map<string /*phone*/,string /*company*/> companies;
Chances are that your "SilverLines.h" actually DOES define something, instead of just declaring it. I'm not going to try and decipher the error message, though :-)
Seems there are some multiple definitions coming due to inclusion of the SilverLines.h twice.
Pl. use a header guard like below in your SilverLines.h header file and then incude it.
This may help.
#ifndef SILVER_H
#define SILVER_H
//Write the contents of SilverLines.h here.
#endif // SILVER_H
You may have another error in your code.
ALso make sure that you are not writing your main or any other piece of code in .h file.
.h file should just contain the prototypes of the functions followed by a semi colon.
Thank you guys I worked it out:
findCompany() is now a global function, and map<string,string> companies is a static field inside it. It compiles great.