Having trouble with constructors which accepts different parameters - c++

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;
};

Related

Can't pass full array value to another function in C++

I am new to c++ & don't know the basics all that well. pls help (sorry if the solution to this is already available, but I couldn't find any)
This is the Error I am getting:
expected primary-expression before ‘]’ token
char CusName[50]=x[];
^
For this code below:
#include <iostream>
using namespace std;
class BankAccount
{
private:
char CusName[50];
char CusId[10];
float accBalance, dep, witd;
public:
void setCusDetails(char x[], char n)
{
char CusName[50]=x[];
}
};
int main()
{
BankAccount customer1;
char cus1Name[50];
cin>>cus1Name;
customer1.setCusDetails(cus1Name, 50);
return 0;
}
Your char array looks like a string. Try using std::string instead and prefer using const references for function parameters.
If you want to use char arrays, and if your point was to copy a null-terminated string by value, then use functions like strncpy.
Using std::string may be easier for you to hide the burden of memory allocation and discover the language step by step.
You can instead use string to input and pass values.
#include <iostream>
using namespace std;
class BankAccount
{
private:
string CusName; //CusName of type string
char CusId[10];
float accBalance, dep, witd;
public:
void setCusDetails(string str, char n) //parameter str of type string
{
CusName=str; //Assign it to the already declared 'CusName' variable.
}
};
int main()
{
BankAccount customer1;
string cus1Name;
cin>>cus1Name;
customer1.setCusDetails(cus1Name, 50);
return 0;
}

2 classes with the same name within namespaces

I have gone back to learning C++ doing some old university courses and I am now currently learning parametric polymorphism as well as creating my own namespaces.
The exercise states that I have to make a namespace called "Federation" which has a class called "Ship" that takes values and one default value that never changes.
inside the federation namespace there is also a "Starfleet" namespace in which we also have a "Ship" class, the only difference is that the default value stated before can be specified by the user.
Here is the code:
Federation.hpp
#include <iostream>
#include <string>
#include <cstring>
namespace Federation
{
namespace Starfleet
{
class Ship
{
public:
Ship(int length, int width, std::string name, short maxWarp);
~Ship();
private:
int _length;
int _width;
std::string _name;
short _maxWarp;
};
};
class Ship
{
public:
Ship(int length, int width, std::string name);
~Ship();
private:
int _length;
int _width;
std::string _name;
}
};
Federation.cpp
#include "Federation.hpp"
using namespac std;
Federation::Starfleet::Ship::Ship(int length, int width, string name, short maxWarp): _length(length), _width(width), _name(name), _maxWarp(maxWarp)
{
cout << "Starfleet Ship Created." << endl;
}
Federation::Starfleet::Ship::~Ship()
{
}
Federation::Ship::Ship(int length, int width, string name, int speed = 1): _length(length), _width(width), _name(name)
{
cout << "Regular Ship Created"
}
Federation::Ship::~Ship()
{
}
main.cpp
#include "Federation.hpp"
int main(int ac, char **av)
{
Federation::Starfleet::Ship mainShip(10, 10, "Starfleet Ship", 20);
Federation::Ship smallShip(5, 5, "Small Ship");
}
When compiling I get this Error: "prototye for Federation::Ship::Ship(int, int, std::__cxx11::string, int) does not match any class in Federation::Ship"
I am totally lost as to what this means, when I look at my functions on my hpp file all of them seem to be correct, so I don't really understand what exactly I'm doing wrong in this case.
This has nothing to do with namespaces. You declare the c'tor with a certain prototype in the header:
Ship(int length, int width, std::string name);
And then randomly add a parameter with a default argument in the implementation file:
Federation::Ship::Ship(int length, int width, string name, int speed = 1)
Argument types are a part of any function or constructor's signature. So you have a declaration and definition mismatch. Declare the extra parameter in the header (along with the default argument).
Ship(int length, int width, string name, int speed = 1);
// and
Federation::Ship::Ship(int length, int width, string name, int speed)

C++ Request for member, which is of non-class type (when using class template, can't define in the main)

**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.

error: undefined reference to class::method (main, header file, source code)

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

C2061 - Circular dependency

How to avoid circular dependency on these code:
Mechanic.cpp:
#include "stdafx.h"
#include "Characters.h"
#include "Monsters.h"
using namespace characters;
using namespace monsters;
using namespace std;
void character::character_atack(character const cha, monster &monst)
{
if (cha.dexterity + k(20) >= monst.defense)
monst.health = monst.health - cha.strength;
}
int k(int const max)
{
return (rand() % max);
}
void monster::monster_atack(character &cha, monster const monst)
{
if (monst.atack + k(20) >= cha.dexterity)
cha.health = cha.health - monst.damage;
}
Monsters.h:
#include <iostream>
#include <string>
namespace monsters
{
using namespace std;
class monster{
protected:
string name;
public:
int atack;
int damage;
int health;
int defense;
monster(int atk, int dmg, int hp, int def) : atack(atk), damage(dmg),
health(hp), defense(def) {}
~monster();
void monster_atack(character &cha, monster const monst);
};
class greenskins:monster{
greenskins(int atk, int dmg, int hp, int def) : monster(atk, dmg, hp, def) {}
};
}
Characters.h:
#include <iostream>
#include <string>
#include <vector>
namespace characters
{
using namespace std;
class character{
protected:
int level;
int experience;
string name;
public:
int health;
int strength;
int intelligence;
int dexterity;
struct position{
int x;
int y;
}pos;
character(int str, int in, int dex) : strength(str), intelligence(in),
dexterity(dex), level(1), experience(0) {
cout << "What's your name?" << endl;
cin >> name; }
~character();
void info_character();
void character_atack(character const cha, monster &monst);
};
}
The compilator gives me errors like this:
Error 1 error C2061: syntax error : identifier 'monster'
or
Error 9 error C2511: 'void monsters::monster::monster_atack(characters::character &,const monsters::monster)' : overloaded member function not found in 'monsters::monster'
The issue is that character has a function that takes a monster& and monster has a function that takes a character&, but you don't declare the other class in either case. Thankfully, since you just pass the classes as arguments in both places (as opposed to having them be members or something), it is sufficient to forward-declare both classes in both places:
// in character.h
namespace monsters {
class monster; // just fwd-declare
}
namespace characters {
class character {
// as before
};
}
And similar in the other file.
[update] Also, you're just referencing monster inside of class character in the header file, you need to qualify it as monsters::monster.
The first error comes from the following line in Characters.h
void character_atack(character const cha, monster &monst);
You include Characters.h into your .cpp file before you include the Monsters.h and thus the type monster is not yet known. To fix this, change your Characters.h to look like this:
... //includes
namespace monsters {
class monster;
}
namespace characters {
class character {
... //class definition
}
}
The second error is a not matching signature. You are declaring following method:
void monster_atack(character &cha, monster const monst)
but defining
void monster::monster_atack(character &cha, const monster monst)
At least that is what the compiler said.
I would suggest to change the signature to:
void monster_atack(character &cha, const monster& monst)
to prevent needless copy operations. (depending on optimization of course)