I am writing c++ code to implememt universal hash function, but it doesn't recognize the parameters, here is the code:
#include <math.h>
#include <cmath>
#include "hash.h"
#include <iostream>
using namespace std;
#include <string>
HASH::HASH(){
a=23;
b=88;
n=100;
p=997;
products=new product[n];
}
HASH::~HASH(){
delete []products;
}
HASH::HASH(int aa,int bb,int nn, int pp){
a=aa;
b=bb;
n=nn;
p=pp;
products=new product[n];
}
int HF(int key){
int index;
int h;
h=((((a*key)+b)% p)% n);
}
in HF function,it tells me that the parameters a,b,n,p are undefined. I defined them in the header file like this:
class HASH {
private:
int a,b,n,p;
product* products;
public:
HASH();
HASH(int aa,int bb, int nn, int pp);
~HASH();
bool insert(product s);
bool retrieve(int id,product &product);
bool updateName(int id);
bool updateCost(int id);
bool updateQuantity(int id);
bool remove(product &d);
int getNumberOfProducts();
};
int HF(int key);
First, never define a variable with a single char, that you will use a lot, or in class. If you wanna find it in code, it will be impossible - you will stop one each "a" char. Name it something readable.
Second, HF is not a member of class HASH, it can't see private variables of other classes.
Add to public part of HASH class
int HF(int key);
change procedure to
int HASH::HF(int key){ ...
and it will work
Add int HF to the public section of your class and in the file hash.cpp use int HASH:HF instead of int hash.
I noticed a small bug: your function HF doesn't return value - add return statement to HF function.
Related
I am new to C++ and I am having trouble with class and header files. I am trying to create a constructor to accept various pokemon stats such as strings and integers. I used to code in java and constructors were fairly simple to assign.
Pokemons.h
#ifndef POKEMONS_H
#define POKEMONS_H
#include <string>
#include <iostream>
using namespace std;
class Pokemons {
public:
Pokemons();
};
#endif /* POKEMONS_H */
Pokemons.cpp
#include "Pokemons.h"
#include <string>
using namespace std;
string pokemonName;
string pokemonType1;
string pokemonType2;
int pokemonHP;
int pokemonAttack;
int pokemonDefence;
int pokemonSPAttack;
int pokemonSPDefence;
int pokemonSpeed;
Pokemons::Pokemons(string nm, string tp1, string tp2, int hp, int atk,
int def, int satk, int sdef, int spd) {
pokemonName = nm;
pokemonType1 = tp1;
pokemonType2 = tp2;
pokemonHP = hp;
pokemonAttack = atk;
pokemonDefence = def;
pokemonSPAttack = satk;
pokemonSPDefence = sdef;
pokemonSpeed = spd;
}
main.cpp
#include <iostream>
#include "Pokemons.h"
int main(){
Pokemons p001;
p001.Pokemons("Bulbasaur", "Grass", "None", 31,23,45,43,45,12);
return 0;
}
I am getting the following errors :
Pokemons.cpp:32:9: error: prototype for 'Pokemons::Pokemons(std::string, std::string, std::string, int, int, int, int, int, int)' does not match any in class 'Pokemons'
Pokemons::Pokemons(string nm, string tp1, string tp2, int hp, int atk, int def, int satk, int sdef, int spd) {
In file included from Pokemons.cpp:14:0:
Pokemons.h:21:7: error: candidates are: constexpr Pokemons::Pokemons(Pokemons&&)
class Pokemons {
Pokemons.h:21:7: error: constexpr Pokemons::Pokemons(const Pokemons&)
Pokemons.cpp:30:9: error: Pokemons::Pokemons()
Pokemons::Pokemons(){}
There are three problems here. First, your constructor is declared as Pokemons();, taking zero arguments, but you have a constructor defined as taking many arguments, and so their signatures don't match, and ultimately, because of function overloading in C++, they refer to different functions. Try declaring the constructor as follows in your header file:
class Pokemons {
public:
Pokemons(string nm, string tp1, string tp2, int hp, int atk,
int def, int satk, int sdef, int spd);
};
Now both the definition and declaration should refer to the same function.
The second problem is here:
Pokemons p001;
This implicitly calls the constructor with no arguments. It's important to understand that many functions get called in C++ even though they haven't been explicitly named. To fix this, you should initialize p001 as follows:
Pokemons p001("Bulbasaur", "Grass", "None", 31,23,45,43,45,12);
You should also remove p001.Pokemons("Bulbasaur", "Grass", "None", 31,23,45,43,45,12); on the following line. Now, the compiler can match this call to your constructor taking many arguments.
The third problem for now is that pokemonName all the way through pokemonSpeed are defined outside the Pokemons class, in global scope. This has a similar effect to making a member static in Java. These should be placed inside your class definition, to make them instance members:
class Pokemons {
public:
Pokemons(string nm, string tp1, string tp2, int hp, int atk,
int def, int satk, int sdef, int spd);
private:
string pokemonName;
string pokemonType1;
string pokemonType2;
int pokemonHP;
int pokemonAttack;
int pokemonDefence;
int pokemonSPAttack;
int pokemonSPDefence;
int pokemonSpeed;
};
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...
**On my main i can't add a note on my new Object of the Class Trabalho
ass.add_nota(num);
**
There is a error on my compilation.
My "Trabalho.h" code:
#include <string>
#include <vector>
#include <iostream>
//#include "Enunciado.h"
//#include "Pessoa.h"
using namespace std;
class Estudante;
class Enunciado;
template <class T>
class Trabalho{
static int id_auxiliar;
string texto;
int ano;
int id;
vector<float> calif;
T* Enun;
vector<Estudante*> estudantes;
vector<Enunciado*> enunciados;
public:
Trabalho();
Trabalho(string texto, vector<Estudante*> est, T* en, int ano);
~Trabalho();
void set_texto(string texto);
string get_texto();
void add_nota(float nota);
void add_enun(Enunciado* en){Enun = en;};
int get_id(){return id;};
int get_ano() {return ano;};
void reutilizar(int id_enun);
vector<float> get_calif() {return calif;};
vector<Estudante*> get_estudantes() {return estudantes;};
Enunciado* get_enunciado() {return Enun;};
};
#endif
And my main code:
int main(int argc, char const *argv[]) {
int n;
int m;
Pesquisa ah();
float num = 1.1;
Trabalho<Pesquisa> ass();
Trabalho<Pesquisa>* tass = new Trabalho<Pesquisa>();
ass.add_nota(num);
tass->add_nota(num);
#ifndef ENUNCIADO_H_
#define ENUNCIADO_H_
#include "trabalho.h"
#include "Pessoa.h"
#include <string>
using namespace std;
class Enunciado
{
static unsigned int id_auxiliar;
const unsigned int id;
string titulo;
string descricao;
vector<int> anos_utilizados;
static unsigned int max_util;
public:
Enunciado(string titulo, string descricao);
virtual ~Enunciado();
int get_id(){return id;};
void set_titulo(string titulo);
string get_titulo();
void set_descricao(string descricao);
string get_descricao();
vector<int> get_anos_utilizados();
void mod_max_util(int a);
};
class Pesquisa: public Enunciado{
vector<string> ref;
public:
Pesquisa(string tit, string des, vector<string> refe);
};
class Analise: public Enunciado{
vector<string> repositorios;
public:
Analise(string tit, string des, vector<string> repos);
};
class Desenvolvimento: public Enunciado{
public:
Desenvolvimento(string tit, string des);
};
#endif
Both ways when i create a new Trabalho when i define my type (pesquisa is a class type on #include "Enunciado.h".
This is the two erros that appears:
"Description Resource Path Location Type
request for member 'add_nota' in 'ass', which is of non-class type 'Trabalho()' Test.cpp /Trabalho1/src line 42 C/C++ Problem
"
And:
Description Resource Path Location Type
Method 'add_nota' could not be resolved Test.cpp /Trabalho1/src line 42 Semantic Error
Can anyone help?
Thank you !
Your error is in trying to call the default constructor as
Pesquisa ah();
or
Trabalho<Pesquisa> ass();
Unfortunately, C++ is very misleading in this and it would declare your variable ass of type Trabalho<Pesquisa>(), which means "a function of zero arguments returning Trabalho<Pesquisa>" and that's exactly that the compiler error says: a function type is not a class type and as such does not have the member add_nota. Indeed, it does look exactly like a function declaration, if you look at it that way:
int main();
^ ^ ^
type arguments
name
It's a very common mistake, especially for those coming from a Java background. But it can easily catch a C++ programmer off guard as well. More information can be found here or here or here, you can see that the same error message has perplexed a good many people.
If you have a compiler conforming to the C++11 language revision, try replacing all those occurrences by
Trabalho<Pesquisa> ass{};
If not, just leave
Trabalho<Pesquisa> ass;
Unlike in Java, this does not mean that the variable will stay uninitialized. It's the C++ way to call a default (zero-argument) constructor.
Source File:
#include "WeatherForecaster.h"
#include <iostream>
using namespace std;
WeatherForecaster::WeatherForecaster(string d, string fd, int h, int l, int hum,int avgw, string avgwd, int maxw, string maxwd, double p){
string day=d;
string forecastDay=fd;
int highTemp=h;
int lowTemp =l;
int humidity=hum;
int avgWind= avgw;
string avgWindDir=avgwd;
int maxWind=maxw;
string maxWindDir= maxwd;
double recip=p;
}
WeatherForecaster::WeatherForecaster(){
//dtor
}
void AddDaytoData(ForecastDay){
}
Header File:
#ifndef WEATHERFORECASTER_H
#define WEATHERFORECASTER_H
#include <iostream>
using namespace std;
struct ForecastDay{
std::string day;
std::string forecastDay;
int highTemp;
int lowTemp;
int humidity;
int avgWind;
std::string avgWindDir;
int maxWind;
std::string maxWindDir;
double precip;
};
class WeatherForecaster
{
public:
WeatherForecaster(string, string, int, int,
int,int, string, int, string , double );
WeatherForecaster();
void addDayToData(ForecastDay);
void printDaysInData(); //prints the unique dates in the data
void printForecastForDay(std::string);
void printFourDayForecast(std::string);
double calculateTotalPrecipitation();
void printLastDayItRained();
void printLastDayAboveTemperature(int);
void printTemperatureForecastDifference(std::string);
void printPredictedVsActualRainfall(int);
std::string getFirstDayInData();
std::string getLastDayInData();
protected:
private:
int arrayLength;
int index;
ForecastDay yearData[984]; //data for each day
};
#endif // WEATHERFORECASTER_H
ERROR: My error happens when I declare try to reach a function in my source file after declaring an instance of the class Weather Function.
ex:
WeatherForecaster wf;
wf.AddDayToData();
//undefined reference to 'WeatherForecaster::AddDaytoData'
I am not entirely sure where the lack of referencing is happening, also I have the header included in main, as well as all other relevant additions.
Edit: I added a function as an example
In your cpp file you need to scope your member function definition
WeatherForecaster::AddDayToData(ForecastDay)
instead of
AddDayToData(ForecastDay)
Also in your call you must pass an argument since it's not optional
I try to compile the following code:
#include <cppunit/extensions/HelperMacros.h>
#include "tested.h"
class TestTested : public CppUnit::TestFixture
{
CPPUNIT_TEST_SUITE(TestTested);
CPPUNIT_TEST(check_value);
CPPUNIT_TEST_SUITE_END();
public:
void check_value();
};
CPPUNIT_TEST_SUITE_REGISTRATION(TestTested);
void TestTested::check_value() {
tested t(3);
int expected_val = t.getValue(); // <----- Line 18.
CPPUNIT_ASSERT_EQUAL(7, expected_val);
}
As a result I get:
testing.cpp:18:32: Error: void-value is not ignored where it should be
EDDIT
To make the example complete I post the code of the tested.h and tested.cpp:
tested.h
#include <iostream>
using namespace std;
class tested {
private:
int x;
public:
tested(int int_x);
void getValue();
};
tested.cpp
#include <iostream>
using namespace std;
tested::tested(int x_inp) {
x = x_inp;
}
int tested::getValue() {
return x;
}
you declare void getValue(); in the class tested.. change to int getValue();.
A void function cannot return a value.
You are getting a value of int from the API getValue(), hence it should return an int.
Your class definition doesn't match the implementation:
In your header you've declared it in the following way (as an aside, you might want to look into some naming conventions).
class tested {
private:
int x;
public:
tested(int int_x);
void getValue();
};
You've declared getValue() as void, i.e no return. Doesn't make much sense for a getter to return nothing, does it?
However, in the .cpp file you've implemented getValue() like so:
int tested::getValue() {
return x;
}
You need to update the getValue() method signature in the header type so that its return type matches the implementation (int).