Initialize a vector of objects in C++ [duplicate] - c++

This question already has an answer here:
Bizarre issue when populating a list with objects in C++?
(1 answer)
Closed 4 years ago.
my problem is the following: I have a class named City with the paramters Name, Latitude and Longitude. In my main class I want to initialize a vector with some cities.
Here is my City Header File:
using namespace std;
#define RADIUS 6378.137
#define PI 3.14159265358979323846
class City {
public:
City(string _name, double _latitude, double _longitude) {
name = _name;
longitude = _longitude * PI / 180.0;
latitude = _latitude * PI / 180.0;
}
~City() { };
private:
double longitude;
double latitude;
string name;
double earthRadius = RADIUS;
};
And then there is my main class file:
#include <iostream>
#include <vector>
#include "Route.h"
using namespace std;
vector<City> initRoute { (("Boston", 42.3601, -71.0589),
("Houston", 29.7604, -95.3698), ("Austin", 30.2672, -97.7431),
("San Francisco", 37.7749, -122.4194), ("Denver", 39.7392, -104.9903),
("Los Angeles", 34.0522, -118.2437), ("Chicago", 41.8781, -87.6298)) };
int main() {
//for each(City city in initRoute)
//city.printCity;
system("pause");
return 0;
}
When I try to compile it puts out the Error C2398:
Error C2398 Element "1": Die Conversion from "double" to "unsigned int"
requires a restrictive conversion.
I have the feeling that my initialization of my vector is wrong but I dont know what to change.
Thanks for your help :)

You have to specify the type of the object when you're adding it to the vector.
i.e.
vector<City> initRoute { City("Boston", 42.3601, -71.0589),
City("Houston", 29.7604, -95.3698), ... };
Or
You can use the {} to represent the object without explicitly mentioning the class since your vector is holding City objects (just like you do with structs).
i.e.
vector<City> initRoute { {"Boston", 42.3601, -71.0589},
{"Houston", 29.7604, -95.3698}, ... };

Related

How to access a atribute in a different class

I'm doing a program that just have to print value of the variables, i think the first class is working, the 'm_valor' is printed like i want , but the second class should be printing 'm_valor + m_valorAdicional', but it is printing just the value of 'm_valorAdicional':
#ifndef INGRESSO_H
#define INGRESSO_H
#include <iostream>
using namespace std;
class Ingresso
{
protected:
float m_valor;
public:
Ingresso(): m_valor(0){};
Ingresso(float valor): m_valor(valor){};
~Ingresso(){};
float getValor() const {return m_valor; };
};
class IngressoVip : public Ingresso
{
private:
float m_valorAdicional;
public:
IngressoVip(): m_valorAdicional(0){};
IngressoVip(float valor): m_valorAdicional(valor){};
~IngressoVip(){};
float getValor(){return m_valorAdicional +=m_valor;};
};
#endif
main.cpp:
#include "Ingresso.hpp"
int main()
{
Ingresso a(10);
IngressoVip b(5);
out<<"valor Ingresso: "<<a.getValor()<<endl;
cout<<"valor IngressoVip: "<<b.getValor()<<endl;
return 0;
}
I think this should be easy, but i just don't know what i have to do to work like i want.
You should use +, not +=. What += does here in this line:
return m_valorAdicional +=m_valor;
is it adds the value of m_valor to m_valorAdicional, changing the value of m_valorAdicional, and then returning this new value. If you don't want to change the values of the variables use +.

[C++]Constructor doesn't detect components [duplicate]

This question already has an answer here:
C++ constructor definition differences in the code given below [closed]
(1 answer)
Closed 6 years ago.
I'm beginner in OOP and I have problem with definition of constructor.
headfile.h:
#ifndef RACHUNEK_H_INCLUDED
#define RACHUNEK_H_INCLUDED
#include <string>
class Rachunek
{
std::string surname;
std::string nr_account;
double balance;
public:
Rachunek();
Rachunek(std::string & name,std::string & nr,double s = 0.0);
~Rachunek(){};
void show();
void give(const double m);
void get(const double m);
};
#endif // RACHUNEK_H_INCLUDED
file .cpp:
#include <iostream>
#include <string>
#include "rachunek.h"
using namespace std;
Rachunek::Rachunek() //default
{
surname = "not specified";
nr_account = "0000-0000-0000-0000";
balance = 0.0;
}
Rachunek::Rachunek(string & name, string & nr, double s = 0.0) //mysecond
{
surname = name;
nr_account = nr;
balance = s;
}
the problem is the definition of a constructor. I don't know what is wrong...
the problem is the definition of a constructor. I don't know what is wrong...
You are not allowed to have default values in the definition of the function. Default values are allowed only in the declaration. Use:
Rachunek::Rachunek(string & name, string & nr, double s) :
surname(name),
nr_account(nr),
balance(s)
{
}
I suggest changing the implementation of the other constructor to initialize the member variables using initializer list syntax.
Rachunek::Rachunek() :
surname("not specified"),
nr_account("0000-0000-0000-0000"),
balance(0.0)
{
}
If you are able to use a C++11 compiler that can be further simplified by using a delegating constructor.
Rachunek::Rachunek() : Rachunek("not specified", "0000-0000-0000-0000", 0.0)
{
}

vector wont push class function c++ [duplicate]

This question already has answers here:
Updating vector of class objects using push_back in various functions
(2 answers)
Closed 7 years ago.
I am attempting to make a text adventure sort of game, and I would like to avoid a bunch of conditionals, so I am trying to learn about the classes stuff and all that. I have created several classes, but the only ones that pertain to this problem are the Options class and the Items class. My problem is that I am trying to push_back() a object into a vector of the type of that object's class and it apparently doesn't happen yet runs until the vector is attempted to be accessed. This line is in main.cpp. I have researched on this, but I have not been able to find a direct answer, probably because I'm not experienced enough to not know the answer in the first place.
The program is separated into 3 files, main.cpp, class.h, and dec.cpp.
dec.cpp declares class objects and defines their attributes and all that.
main.cpp:
#include <iostream>
#include "class.h"
using namespace std;
#include <vector>
void Option::setinvent(string a, vector<Item> Inventory, Item d)
{
if (a == op1)
{
Inventory.push_back(d);
}
else {
cout << "blank";
}
return;
}
int main()
{
vector<Item> Inventory;
#include "dec.cpp"
Option hi;
hi.op1 = "K";
hi.op2 = "C";
hi.op3 = "L";
hi.mes1 = "Knife";
hi.mes2 = "Clock";
hi.mes3 = "Leopard!!";
string input1;
while (input1 != "quit")
{
cout << "Enter 'quit' at anytime to exit.";
cout << "You are in a world. It is weird. You see that there is a bed in the room you're in." << endl;
cout << "There is a [K]nife, [C]lock, and [L]eopard on the bed. Which will you take?" << endl;
cout << "What will you take: ";
cin >> input1;
hi.setinvent(input1, Inventory, Knife);
cout << Inventory[0].name;
cout << "test";
}
}
dec.cpp just declares the Item "Knife" and its attributes, I've tried pushing directly and it works, and the name displays.
class.h
#ifndef INVENTORY_H
#define INVENTORY_H
#include <vector>
class Item
{
public:
double damage;
double siz;
double speed;
std::string name;
};
class Player
{
public:
std::string name;
double health;
double damage;
double defense;
double mana;
};
class Monster
{
public:
double health;
double speed;
double damage;
std::string name;
};
class Room
{
public:
int x;
int y;
std::string item;
std::string type;
};
class Option
{
public:
std::string op1;
std::string op2;
std::string op3;
std::string mes1;
std::string mes2;
std::string mes3;
void setinvent(std::string a, std::vector<Item> c, Item d);
};
#endif
Any help would be greatly appreciated! I realize that the whole structure may need to be changed, but I think that this answer will help even if that may be the case.
My problem is that I am trying to push_back() a object into a vector of the type of that object's class and it apparently doesn't happen yet runs until the vector is attempted to be accessed.
it happen but only inside your setinvent method:
void Option::setinvent(string a, vector<Item> Inventory, Item d)
^^^^^^^^^^^^ - passed by value
Inventory is passed by value which means it is a local vector variable in setinvent function. If you want to modify vector from main function, make it a reference:
void Option::setinvent(string a, vector<Item>& Inventory, Item d)
^^^^^^^^^^^^ - passed by reference, modifies vector from main
now Inventory is local reference variable. Also dont forget to change setinvent declaration in header file.

How can I call the data type from the function of a class

I defined a class as well as member function. And now I would like to call the data type(x.dat) imported from outside.
How could I do that?
It would be something like this:
class abs{
private:
...
public:
...
void function(data){ //here i would like to use the external data x.dat
...
}
}
Yes, Keith is correct.
What you want is a static variable that maintains the same data across all objects of that type. You don't necessarily need a function to do this.
#include <iostream>
#include <string>
using namespace std;
class abs
{
private:
public:
static double data[3];
};
double abs::data[3]={}; //instantiate the variable
int main () {
abs::data[0]=5.0;
cout<<abs::data[0]; //outputs 5
}
Static variables are associated with the class definition, and not the instantiated objects of that type so as long as the program is active it will be stored in memory as part of the class.
Firstly, tremendous thanks to all of you, especially #Mir
I get it running now, although I don't know why does someone give me a negative!?
I would like to make a summary here, for myself, and future readers.
My question is this:
I have a stored data(double[1000]), which is a file of 'x.dat';
And I define a class 'abs' in the header file, as well as its member function 'function';
And 'function' would like to call data as a inputting parameter.
How to do these?
With the help of Mir, it's working now like this, hope it would help someone:
1.abs.h
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class abs
{
private:
public:
static double data[1000];
double function(double xa[]){
for(int i=0;i<1000;i++){
res += xa[i] * 2.0;
}
return res;
}
};
2.abs.cpp
#include "abs.h"
double abs::data[1000]={}; //instantiate the variable
3.main.cpp
#include "abs.h"
int main () {
abs a = abs();
for(int i = 0; i < 1000, i++){
ifstream fs("x.dat")
fs >> abs::data[i];
cout << abs::data[i]; //outputs all data
}
double Value = a.function(data);
cout<< Value<<endl;
}

C++ creating a class object [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I am having issues creating an object for my class, I am getting errors trying to create the class object with the defined data members.
// class header for employee
#pragma once
#include <string>
#include <iostream>
class Employee
{
private:
std::string name;
int empnum;
std::string address;
std::string phone;
double hourwage;
double hoursworked;
public:
Employee(void);
Employee(int, std::string , std::string, std::string, double, double);
double gethourwage () const;
double gethoursworked () const;
double printcheck () const;
std::string getphone() const;
std::string getname() const;
std::string getaddress() const;
};
// end of header
// employee class.cpp
#include "Employee.h"
#include <string>
#include <iostream>
Employee::Employee(void)
{
int empnum = 0;
double hourwage = 0.0;
double hoursworked = 0.0;
}
Employee::Employee(int num, std::string nme, std::string addres, std::string phon, double hourpay, double hrswrked)
{
num = empnum;
nme = name;
addres = address;
phon = phone;
hourpay = hourwage;
hrswrked = hoursworked;
}
double Employee::gethourwage() const
{
return hourwage;
}
double Employee::gethoursworked() const
{
return hoursworked;
}
double Employee::printcheck() const
{
double pay = 0.0;
double hrspay = hourwage;
double hrswork = hoursworked;
return hoursworked;
}
// end of employee.cpp
// main
#include <iostream>
#include <algorithm>
#include <numeric>
#include <vector>
#include <iterator>
#include <string>
#include "Employee.h"
using namespace std;
int main( )
{
int num1 = 10210;
double hourwage = 20.2;
double hourworked = 32.3;
string steve;
Employee emp(num1, steve, 58s200w, 90210, hourwage, hourworked);
cout << "" << emp.getaddress();
system("PAUSE");
return 0;
} // end of main
"Employee emp(num1, steve, 58s200w, 90210, hourwage, hourworked);" towards the bottom is the line I am having the issue with. I am not sure if I am entering it in the wrong order, or something else.
Thanks in advance for any help.
You should enter strings in double quotes:
Employee emp(num1, "steve", "58s200w", "90210", hourwage, hourworked);
Edit 1 (tried to explain the difference between const char * and std::string, as #Alex suggested)
Literal strings in the snippet above are of type const char *, which is a low-level entity inherited from the C language. const char * is a pointer to memory area which holds consecutive values of type const char.
std::string is a higher-level wrapper around C-style strings intended to provide more «user-friendly» API and solve some problems of C-style strings (e.g., dynamic allocation and automatic memory cleanup).
Because the std::string class has a constructor which takes a const char * parameter, literal strings passed to the Employee constructor are implicitly converted to std::string's
Your Employee class constructor is
Employee::Employee(int num, std::string nme, std::string addres, std::string phon, double hourpay, double hrswrked)
and you are calling it as
Employee emp(num1, steve, 58s200w, 90210, hourwage, hourworked);
You can directly see the difference, Employee class constructor expecting 2nd, 3rd and 4th argument as String. So you have to pass these arguments as string. Either you have to declare string as hourwage, hourworked variables as you defined or you have to pass arguments as nameless above explained.