I am trying to write a class with a map to keep a registry with unique ID for later accessing the objects. All compiled fine till i wrote the for loop in main trying to access objects of the class and their data. I am at a loss what is exactly wrong. I declared all static but doesn't work. I have been trying for several hours now but couldn't solve it. I know the problem is in the map as that is new for me, but i can't seem to find the issue. Hope someone sees what is wrong in my code.
#include <iostream>
#include <map>
#include <cassert>
#include <string>
#include <algorithm>
using namespace std;
class vertegenwoordiger{
public:
vertegenwoordiger(int id, string x, int y): ID(id), name(x),aantalpc(y) {
addtoregistry(this);
cout << "Vertegenwoordiger " << x << " is aangemaakt met " << y << " aantal verkochte pc's " << endl;
gemiddeldeverkoop = (gemiddeldeverkoop + y) / id;
}
static map<int, vertegenwoordiger*>registryMap; // PROBLEM HERE I GUESS
static void addtoregistry(vertegenwoordiger* object){
registryMap[object->ID] = object;
}
static void removefromregistry(vertegenwoordiger* object){
registryMap.erase(object->ID);
}
static vertegenwoordiger* findbymap(int id){
return registryMap[id];
} // MAYBE THIS FUNCTION IS NOT CORRECT ASWELL????
void commissionfixed (vertegenwoordiger* obj){
commissievast = obj->aantalpc*winstperpc;
}
void commissionextra (vertegenwoordiger*obj){
if (obj->aantalpc>gemiddeldeverkoop){
commissieplus = (obj->aantalpc - gemiddeldeverkoop) * 37;
}
}
static const int winstperpc;
static int gemiddeldeverkoop;
const int ID;
protected:
string name;
int aantalpc;
int commissievast;
int commissieplus;
};
const int vertegenwoordiger::winstperpc = 150;
int vertegenwoordiger::gemiddeldeverkoop = 0;
int main()
{
for (int i=0; i<4; i++){
string naam;
int pc;
cout << "geef naam in :";
cin >> naam;
cout << "geef aantal pc op :";
cin >> pc;
vertegenwoordiger* test = new vertegenwoordiger (i+1,naam,pc);
cout << "volgende aub : " << endl;
}
for (int i=1; i<4 ; i++){
vertegenwoordiger* val = vertegenwoordiger::findbymap(i); // I GUESS THE PROBLEM IS RELATED TO THIS LINE
vertegenwoordiger::commissionfixed (val);
vertegenwoordiger::commissionextra (val);
}
return 0;
}
#include <iostream>
#include <map>
#include <cassert>
#include <string>
#include <algorithm>
using namespace std;
class vertegenwoordiger{
public:
vertegenwoordiger(int id, string x, int y): ID(id), name(x),aantalpc(y){
addtoregistry(this);
cout << "Vertegenwoordiger " << x << " is aangemaakt met " << y << " aantal verkochte pc's " << endl;
gemiddeldeverkoop = (gemiddeldeverkoop + y) / id; }
static map<int, vertegenwoordiger*>registryMap;
static void addtoregistry(vertegenwoordiger* object){ registryMap[object->ID] = object; }
static void removefromregistry(vertegenwoordiger* object){ registryMap.erase(object->ID); }
static vertegenwoordiger* findbymap(int id){ return registryMap[id]; }
void commissionfixed (){
commissievast = this->aantalpc*winstperpc; }
void commissionextra (){
if (this->aantalpc>gemiddeldeverkoop){ commissieplus = (this->aantalpc - gemiddeldeverkoop) * 37; } }
void readCommission(){
cout << "comission payment is " << this->commissievast << endl;
}
static const int winstperpc;
static int gemiddeldeverkoop;
const int ID;
string name;
protected:
int aantalpc;
int commissievast;
int commissieplus;
};
map<int, vertegenwoordiger*>vertegenwoordiger::registryMap;
const int vertegenwoordiger::winstperpc = 150; int vertegenwoordiger::gemiddeldeverkoop = 0;
int main() {
for (int i=0; i<2; i++){ string naam; int pc; cout << "geef naam in :";
cin >> naam;
cout << "geef aantal pc op :";
cin >> pc;
vertegenwoordiger* test = new vertegenwoordiger (i+1,naam,pc);
cout << "next please : " << endl; }
for (int i=1; i<3 ; i++){
vertegenwoordiger* val = vertegenwoordiger::findbymap(i);
val->commissionfixed ();
val->commissionextra ();
val->readCommission ();
}
return 0; }
Related
#include <iostream>
#include <typeinfo>
#include <string>
#include <cstdlib>
using namespace std;
template <typename First>
class VerifyIfTrue{
protected:
First AG;
int tries = 0;
int vaalue;
int RT;
string whatis;
string lie1;
string lie2;
VerifyIfTrue(string twhatis, string tlie1, string tlie2) : whatis(twhatis), lie1(tlie1), lie2(tlie2)
{input();}
void input(){
if(tries == 0){
cout << "Tell me your " << whatis << "\n";}else{
cout << "Come on, what's your " << whatis << "\n";}
cin >> AG;
if(typeid(AG).name() != typeid(int).name())
{
int x = 0;
AG = x;
cout << "Wrong type" << endl;
++tries;
input();
}else{
int a = AG;
positivetest(a);
}
void positivetest(int RT){
if(RT <=0)
{
cout << lie1 << "\n";
if(tries == 0)
{
++tries;
cout << lie2 << "\n";
}
int y = 0;
AG = y;
++tries;
input();
}else{
vaalue = AG;
}
}
}
...
I get the following error:
cannot convert 'std::__cxx11::basic_string' to 'int' in initialization|
Is there a way around this? I want to either be able to change AG into an int, so it can be passed into int parameters or tested if it's an int; or be able to assign its' value to an int
You might use if constexpr (c++17) with std::is_same:
if constexpr (!std::is_same_v<int, First>) {
int x = 0;
AG = x;
cout << "Wrong type" << endl;
++tries;
input();
} else {
int a = AG;
positivetest(a);
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I tried to print a array of characters using dynamic memory allocation with pointer. If i comment one pf the variables work, but when i tried to print both the program stop.
This is Main CPP.
#include <iostream>
#include "ContactInfo.h"
using namespace std;
int main() {
int n = 0;
char *ph, *nm;
ContactInfo *allcontacts;
cout << "How many people you want to add to phone book? ";
cin >> n;
allcontacts = new ContactInfo[n];
for (int i=0; i < n; i++) {
cout << i + 1 << ") Name: ";
cin >> nm;
allcontacts[i].setName(nm);
cout << i + 1 << ") Phone: ";
cin >> ph;
allcontacts[i].setPhone(ph);
}
cout << setw(8) <<"Name" << setw(8) << "Phone\n";
cout << "------------------------------------------------------\n";
for (int i=0; i < n; i++){
allcontacts[i].display();
}
return 0;
}
CPP
#include "ContactInfo.h"
void ContactInfo::setName(char *n) {
name = new char[strlen(n) + 1];
strcpy(name, n);
}
void ContactInfo::setPhone(char *p) {
phone = new char[strlen(p) + 1];
strcpy(phone, p);
}
ContactInfo::ContactInfo() {
// setName("");
// setPhone("");
}
ContactInfo::ContactInfo(char *n, char *p) {
setName(n);
setPhone(p);
}
ContactInfo::~ContactInfo() {
delete [] name;
delete [] phone;
name = nullptr;
phone = nullptr;
}
const char *ContactInfo::getName() const {
return name;
}
void ContactInfo::display() const {
cout << getName();
cout << getPhoneNumber();
cout << endl;
}
const char *ContactInfo::getPhoneNumber() const {
return phone;
}
HEADER
#include <iostream>
#include <cstring> // Needed for strlen and strcpy
using namespace std;
// ContactInfo class declaration.
class ContactInfo
{
private:
char *name; // The contact's name
char *phone; // The contact's phone number
public:
ContactInfo(char *, char *);
ContactInfo();
void setName(char *);
void setPhone(char *);
~ContactInfo();
const char *getName() const;
const char *getPhoneNumber() const;
void display() const;
};
Ouput
How many people you want to add to phonebook? 2
1) Name: www
1) Phone: 22
Process finished with exit code 0
You are mixing C and C++ code together. You have to use std::string for your input instead of char*. Try following code:
#include <iostream>
#include <vector>
#include <string>
#include <iomanip>
class ContactInfo {
private:
std::string name;
std::string phone;
public:
ContactInfo() {
}
ContactInfo(const std::string &Name, const std::string &Phone) {
name = Name;
phone = Phone;
}
void display() const {
std::cout << name << " " << phone << std::endl;
}
};
int main() {
int n = 0;
std::cout << "How many people you want to add to phone book? ";
std::cin >> n; std::cin.get();
std::vector<ContactInfo> all_contacts;
for (int i = 0; i < n; i++) {
std::string name, phone;
std::cout << i + 1 << ") Name: ";
std::cin >> name;
std::cout << i + 1 << ") Phone: ";
std::cin >> phone;
all_contacts.push_back(ContactInfo(name, phone));
}
std::cout << std::setw(8) << "Name" << std::setw(8) << "Phone" << std::endl;
std::cout << "------------------------------------------------------" << std::endl;
for (auto i : all_contacts) {
i.display();
}
return 0;
}
i was using pointers and new operator for printing different city names. But the Microsoft Visual Studio show that it is Exception thrown:read access violation.
This happen even when i write *ptr=n; or *ptr=20; ,but works properly if i give ptr=&n; (if n is the variable with some value).
Program to display names of cities
#include <iostream>
#include <cstring>
using namespace std;
class city
{
protected:
char *name;
int len;
public:
char *s;
city();
~city();
void getdata()
{
s = new char[20];
cout << "enter the name of city" << endl;
cin >> s;
len = strlen(s);
name = new char[len + 1];
strcpy_s(name, 10, s);
}
void display()
{
cout << *name << endl;
}
private:
};
city::city()
{
len = 0;//initialization
name = NULL;
}
city::~city()
{
delete[]name;
delete[]s;
}
int main()
{
city *obj[10];
int n = 0;
int en=0;
do
{
obj[n] = new city;
obj[n]->getdata();
n++;
obj[n]->display();
cout << "do you want to enter another city?" << endl;
cout << "(enter 1 for yes and 0 for no"<<endl;
cin >> en;
} while (en);
delete[]obj;
system("pause");
return 0;
}
Screenshot of error
Don't manage memory manually! Use STL to forget memory manage!
#include <iostream>
#include <string>
#include <array>
class city
{
protected:
std::string name;
public:
city() = default;
//~city();
void getdata()
{
std::cout << "enter the name of city" << std::endl;
std::cin >> this->name;
}
void display()
{
std::cout << name << std::endl;
}
};
int main()
{
std::array<city, 10> obj;
for(auto&& o : obj)
{
o.getdata();
o.display();
std::cout
<< "do you want to enter another city?" << std::endl
<< "(enter 1 for yes and 0 for no" << std::endl;
int en=0;
std::cin >> en;
if(0 == en) return 0;
}
return 0;
}
https://wandbox.org/permlink/bz4iF3LNDSyUIZPb
Whats wrong with this code to keep on receiving this error?
The error only happened when instead of putting "distanceFormula" in main, I made it it's own class.
#include <iostream>
#include <string>
using namespace std;
class distanceFormula {
public:
int speed;
int time;
int distance;
cout << "What is the speed?" << endl;
cin >> speed;
cout << "How long did the action last?" << endl;
cin >> time;
distance = speed * time;
cout << "The distance traveled was " << distance << endl;
};
int main()
{
distanceFormula ao
ao.distanceFormula;
return 0;
};
The body of the class declaration can only contain members, which can either be data or function declarations, and optionally access specifiers.
Wrap your code inside a function and then call that in main by an object
class distanceFormula {
public:
int speed;
int time;
int distance;
void init()
{
cout << "What is the speed?" << endl;
cin >> speed;
cout << "How long did the action last?" << endl;
cin >> time;
distance = speed * time;
cout << "The distance traveled was " << distance << endl;
}
};
int main()
{
distanceFormula ao;
ao.init();
return 0;
};
If you still have to use a class. Here is how you do it:
#include <iostream>
class distanceFormula
{
private:
int speed; // private
int time; // private
public:
distanceFormula(); // constructor
int getSpeed(); // to get
int getTime(); // to get
int getDistance(); // to get
void setSpeed(int); // to set
void setTime(int); // to set
};
distanceFormula::distanceFormula()
{
this->time = 0;
this->speed = 0;
}
int distanceFormula::getSpeed()
{
return this->speed;
}
int distanceFormula::getTime()
{
return this->time;
}
int distanceFormula::getDistance()
{
return this->time * this->speed;
}
void distanceFormula::setSpeed(int speedVal)
{
this->speed = speedVal;
}
void distanceFormula::setTime(int timeVal)
{
this->time = timeVal;
}
int main()
{
distanceFormula YourObject; // create obj
int SpeedValue;
int TimeValue;
std::cout << "Enter the Speed:";
std::cin >> SpeedValue; // take speed
std::cout << "Enter the Time:";
std::cin >> TimeValue; // take time
YourObject.setSpeed(SpeedValue); // set
YourObject.setTime(TimeValue); // set
std::cout << "This is the distance: " << YourObject.getDistance(); // retrieve result
getchar(); // wait
return 0;
}
This project is not done but currently my group is stuck with the LNK1169 error.
We have a player.h and player.cpp as well as an enemy.h and enemy.cpp and obviously a source.cpp. Somehow the linking between the files got messed up when we combined work on the player and work on the enemy files.
Source.cpp
//#pragma once
#include "Player.h"
#include "Enemy.h"
#include <iostream>
#include <fstream>
#include <string>
#include <time.h>
#include <random>
using namespace std;
int main()
{
cout << "Welcome to our game" << endl;
cout << endl << endl << endl;
int ans = 0;
do {
cout << " Main Menu" << endl;
cout << "-----------------------------" << endl;
cout << "1: Play Game" << endl;
cout << "-----------------------------" << endl;
cout << "2: Exit" << endl;
cout << "-----------------------------" << endl;
cin >> ans;
switch (ans)
{
case 1: //main body of game
case 2:
return 0;
default:
cout << "Please enter 1 to play the game or 2 to exit" << endl;
cin >> ans;
break;
}
} while (ans != 2);
return 0;
}
Enemy.h:
/* UML
Enemies
******************************************
Private
- Health: int
- Attack : int
- Defence : int
******************************************
Public
+ accessor and mutator functions
+ AttackCharacter()
+ DefendCharacter()
+ ChangePosition()
+ LoseHealth()
+ RandomSpawn()
*******************************************
*/
//#pragma once
#ifndef PLAYER_H
#define PLAYER_H
#include <iostream>
#include <string>
using namespace std;
class Enemy
{
private:
int
health,
attack,
defence;
public:
Enemy(int Health, int Attack, int Defence)
{
health = Health; attack = Attack; defence = Defence;
}
int getHealth();
int getAttack();
int getDefence();
void setHealth(int h);
void setAttack(int a);
void setDefence(int d);
//void Attack(Player P1);
};
#endif
Enemy.cpp
#include "Enemy.h"
#include "Player.h"
/*#include <iostream>
#include <string>
using namespace std;
*/
int Enemy::getHealth() { return health; }
int Enemy::getAttack() { return attack; }
int Enemy::getDefence() { return defence; }
void Enemy::setHealth(int h)
{
health = h;
}
void Enemy::setAttack(int a)
{
attack = a;
}
void Enemy::setDefence(int d)
{
defence = d;
}
//void Enemy::Attack(Player P1)
//{
// int h = P1.getHealth();
// int d = P1.getDefence();
// int a = getAttack();
// if (d + h - a > h)
// {
// cout << "You lost 0 health" << endl;
// P1.setHealth(h);
// }
// else
// {
// int h1 = h + d - a;
// cout << "You lost " << h1 - h << " health" << endl;
// P1.setHealth(h1);
// }
//}
The Enemy::attack() function is a work in progress and not really the problem
Player.h:
//#pragma once
#ifndef PLAYER_H
#define PLAYER_H
#include <iostream>
#include <vector>
#include <string>
using namespace std;
struct Armor
{
string name;
char type;
int health;
int attack;
int defense;
Armor() { name = ""; type = ' '; health = 0; attack = 0; defense = 0; } // constructor
};
struct Weapon
{
string name;
char type;
int health;
int attack;
int defense;
Weapon() { name = ""; type = ' '; health = 0; attack = 0; defense = 0; } // constructor
};
struct Shield
{
string name;
char type;
int health;
int attack;
int defense;
Shield() { name = ""; type = ' '; health = 0; attack = 0; defense = 0; } // constructor
};
struct Potion
{
string name;
char type;
int health;
int attack;
int defense;
Potion() { name = ""; type = ' '; health = 0; attack = 0; defense = 0; } // constructor
};
vector<string> type = { "Bronze", "Iron", "Silver", "Steel", "Gold", "Diamond" };
class Player
{
private:
string name;
int initialhealth;
int initialattack;
int initialdefense;
int health;
int attack;
int defense;
public:
Player(string n = " ", int ih = 0, int ia = 0, int id = 0, int h = 0, int a = 0, int d = 0)
{
name = n; initialhealth = ih; initialattack = ia; initialdefense = id; health = h; attack = a; defense = d;
};
Armor armor;
Weapon weapon;
Shield shield;
Potion potion;
string getname();
int getinitialhealth();
int getinitialattack();
int getinitialdefense();
int getHealth();
int getAttack();
int getDefense();
void setname(string n);
void setinitialhealth(int ih);
void setinitialattack(int ia);
void setinitialdefense(int id);
void setHealth(int h);
void setAttack(int a);
void setDefense(int d);
void addITEMS();
void displayPlayer();
void checkARMOR();
};
#endif
Player.cpp:
//#include <iostream>
//#include <string>
#include "Player.h"
//using namespace std;
string Player::getname() { return name; }
int Player::getinitialhealth() { return initialhealth; }
int Player::getinitialattack() { return initialattack; }
int Player::getinitialdefense() { return initialdefense; }
int Player::getHealth() { return health; }
int Player::getAttack() { return attack; }
int Player::getDefense() { return defense; }
void Player::setname(string n) { name = n; }
void Player::setinitialhealth(int ih) { initialhealth = ih; }
void Player::setinitialattack(int ia) { initialattack = ia; }
void Player::setinitialdefense(int id) { initialdefense = id; }
void Player::setHealth(int ih) { health = ih; }
void Player::setAttack(int ia) { attack = ia; }
void Player::setDefense(int id) { defense = id; }
void Player::addITEMS()
{
health = initialhealth + armor.health + weapon.health + shield.health;
attack = initialattack + armor.attack + weapon.attack + shield.attack;
defense = initialdefense + armor.defense + weapon.defense + shield.defense;
}
void Player::displayPlayer()
{
cout << endl;
cout << "=========================" << endl;
cout << " Name : " << name << endl;
cout << " Health : " << health << endl;
cout << " Attack : " << attack << endl;
cout << " Defence : " << defense << endl;
cout << "=========================" << endl;
}
void Player::checkARMOR()
{
if (weapon.name == "Bronze")
{
armor.health = 10;
armor.attack = 5;
armor.defense = 15;
}
if (armor.name == "Iron")
{
armor.health = 100;
armor.attack = 15;
armor.defense = 150;
}
}
Any insight anyone could give into why the LNK1169 error may be popping up would be greatly appreciated. Thank you.
Its simple, you have used
#ifndef PLAYER_H
#define PLAYER_H
twice in Player.h and Enemy.h. Just simply replace:
#ifndef PLAYER_H
#define PLAYER_H
by
#ifndef ENEMY_H
#define ENEMY_H
in Enemy.h
Or use #pragma once preprocessor directive before your declarations in *.h
files
But the real problem is this line in Player.h
std::vector<std::string> type = { "Bronze", "Iron", "Silver", "Steel", "Gold", "Diamond" };
To declare an global variable in a header use the keyword extern.
// Player.h
extern std::vector<std::string> type;
// Player.cpp
std::vector<std::string> type = { "Bronze", "Iron", "Silver", "Steel", "Gold", "Diamond" };
Is it not an option to change this to an enum class?
enum class Types {
Bronze,
Iron,
Silver,
Steel,
Gold,
Diamond
};
And use namespace through out the application?