#ifndef PRODUCTS_H
#define PRODUCTS_H
#include "Products.h"
class Products
{
protected:
static int count;
string name_;
float cost_;
public:
Products() // default ctor
{
name_ = "";
cost_ = 0.0f;
count++;
}
Products(string name , float cost) //parametorized ctor
{
name_ = name;
cost_ = cost;
count++;
}
Products(Products &p )
{
name_ = p -> name_;
cost_ = p -> cost_;
}
~Products()
{}
string getName()
{
return name_;
}
void setName(string name)
{
name_=name;
}
float getCost()
{
return cost_;
}
void setCost(float cost)
{
cost_=cost
}
float CalcTotal(Products *p_products) //Not made yet!
{
float total=0.0f;
for(int i = 0 ; i < count; i++)
{
total += p_products->cost_;
p_products ++;
}
return total;
}
Products read()
{
Products size,*p_products;
cout << "Enter Number of Items To Enter:";
cin >> size;
cout << endl;
p_products = new Products[size];
for(int i = 0 ; i < size; i++)
{
cout << "Enter Name:";
cin >> p_products -> name_;
cout << endl << "Enter Cost";
cin >> p_products -> cost_;
cout << endl;
p_products ++;
}
return p_products;
}
void write(Products *p_products)
{
for(int i = 0 ; i < count ; i++,p_products++)
{
cout<<"Products Name:\t\t"<<p_products->name_<<endl;
cout<<"Products Price:\t\t"<<p_products->cost_<<endl;
}
}
};
#endif
My source code is:
#include <iostream>
#include <string>
#include "Products.h"
using namespace std;
static int Products::count;//declaring static variable
int main()
{
Products *p_products,temp;
*p_products=temp.read();
//temp.write();
system("pause");
delete[] Product;
return 0;
}
But I am getting this error which I can not remove:
error C2146: syntax error : missing
';' before identifier 'name_'
Please help me out!Thanks
You should include the string header file in your first file. It looks like it's complaining that it doesn't know what a string is.
You need to add
#include <string>
and change the type of name_ to
std::string name_;
In Products &p, p is a reference to an object of type Products, it's not a pointer.
You have to use operator ., instead of operator -> in order to access reference fields:
Products(Products &p )
{
name_ = p -> name_;
cost_ = p -> cost_;
}
Try moving this line:
using namespace std;
Above the line where you #include "Products.h". But if you're using string in products.h, you should probably be including etc there instead. Also, I believe "using namespace std" is kinda frowned upon.
in your include file, you must declare the string name_ as std::string name_
You need:
std::string name_;
Also, looks like a missing semicolon here:
void setCost(float cost)
{
cost_=cost
}
You're missing a semicolon in this function:
void setCost(float cost)
{
cost_=cost
}
Related
I am writing some C++ code to create an item of a class i have created inside a vector of another class. I seem to be able to create the items inside the vector but when i try to read a variable of the item inside the vector i get the error
Exception thrown: read access violation.
_Right_data was 0x8.
inside the document xstring.
I think it might have something to do with me not actually creating each team inside the vector.
the code i have written that is relavent is
for (int x = 1; x <= mainLeague.getNumTeams(); x++) {
std::cout << "please enter the name of team " << x << ":";
std::getline(std::cin, currLine);
parsed = parseText(currLine, &posResponsesTeamNames);
if (parsed == 2) {
prepForEnd();
return 1;
}
else if (parsed == 0) goto enterTeamNames;
mainLeague.createTeam(currLine);
}
std::cout << mainLeague.getName(5);
}
#pragma once
#include "team.h"
#include <string>
#include <vector>
#include <iostream>
class league
{
std::vector<team*> teams;
int numTeams, numInitTeams = 0;
const float sysCon = 0.5;
public:
league(int a);
int getNumTeams();
void initVector(int numTeams);
void createTeam(std::string name);
std::string getName(int num);
};
void league::createTeam(std::string name)
{
if (numInitTeams < teams.size()) {
team currTeam = team::team(name);
teams.at(numInitTeams) = &currTeam;
numInitTeams;
}
else {
std::cout << "error max amount of teams already created";
}
}
#pragma once
#include<string>
class team
{
float RD;
int rating;
std::string name;
public:
team(std::string name);
team();
std::string getName();
};
std::string team::getName()
{
return team::name;
}
I got some problem when run my coding. I got 2 separate file to create RetailItem class and create main. I create both in project.
Below are main.cpp
//main
#include "retailitem.h"
#include <iostream>
#include <iomanip>
using namespace std;
using std::cout;
void displayItem(RetailItem *, const int);
int main()
{
const int Item = 3;
RetailItem ritem[Item] ={ { "Jacket", 12, 59.95 },
{ "Designer Jeans", 40, 34.95 },
{ "Shirt", 20, 24.95 } };
//cout << fixed << setprecision(2);
void displayItem(RetailItem *ritem, const int Item){
cout <<" DESCRIPTION UNITS ON HAND PRICE";
cout<<"=================================================================\n";
for (int i = 0; i < Item; i++)
{
cout << setw(12) << ritem[i].getDesc();
cout << setw(12) << ritem[i].getUnits();
cout << setw(8) << ritem[i].getPrice();
}
cout << "===================================================================";
}
return 0;
}
and there one more file retailitem.h
//RetailItem class
#include <string>
using namespace std;
class RetailItem
{
private:
string description;
int unitsOnHand;
double price;
public:
RetailItem(string,int,double);
void setDesc(string d);
void setUnits(int u);
void setPrice(double p);
string getDesc();
int getUnits();
double getPrice();
};
RetailItem::RetailItem(string desc, int units, double cost)
{
description = desc;
unitsOnHand = units;
price = cost;
}
void RetailItem::setDesc(string d)
{
description = d;
}
void RetailItem::setUnits(int u)
{
unitsOnHand = u;
}
void RetailItem::setPrice(double p)
{
price = p;
}
string RetailItem::getDesc()
{
return description;
}
int RetailItem::getUnits()
{
return unitsOnHand;
}
double RetailItem::getPrice()
{
return price;
}
when compile and run main,
[Error] a function-definition is not allowed here before '{' token
[Error] expected '}' at end of input
I don't know what to fix, how can I solve it?
The error message undoubtedly contained a line number that told you where the problem was. That's an important part of describing the problem. But here it happens to be obvious: void displayItem(RetailItem *ritem, const int Item){ is the start of a function definition. You can't define a function inside another function. Move this outside of main.
for example lets have a class or struct name Employee with two constructors, a default constructor and a constructor with parameters two strings and an int. why doesn't the following code work?
Employee *employees = (employee*) malloc(sizeof(Employee)*10);
let's say we have an array, size 10, of type string for first name, last name, and one of type int for salary. how to initialize the data members of each object class using the constructor with the parameters?
for (int i = 0; i < 10; i++)
{
employees[i] = employee(firstname[i], lastname[i], salary[i]);
}
I've been trying to do this for a few days now but wasn't successful. Also, can anyone tell how to do this using c++'s new and delete operator? and also is there a way this can be done using vectors?
Thank you
header file
class employee{
std::string firstname;
std::string lastname;
int salary;
public:
employee(std::string, std::string , int);
employee();
void setFirst(std::string);
void setLast(std::string);
void setSalary(int);
std::string getFirst();
std::string getLast();
int getSalary();
};
employee::employee(std::string x, std::string y, int z)
{
setFirst(x);
setLast(y);
setSalary(z);
}
void employee::setFirst(std::string x)
{
firstname = x;
}
void employee::setLast(std::string y)
{
lastname = y;
}
void employee::setSalary(int z)
{
salary = z > 0 ? z : 0;
}
std::string employee::getFirst()
{
return firstname;
}
std::string employee::getLast()
{
return lastname;
}
int employee::getSalary()
{
return salary;
}
.cpp file
#define MAX 20
using namespace std;
int main(int argc, char* argv[])
{
int n = 1;
cout << "number of employees: ";
cin >> n;
string firstname[MAX];
string lastname[MAX];
double salary[MAX];
float raise[MAX];
for (int i = 0; i < n; i++)
{
cout << "Employee " << i + 1 <<endl;
cout << "-----------\n";
cout << "First Name: ";
cin >> firstname[i];
cout << "Last Name: ";
cin >> lastname[i];
cout << "Monthly Salary: ";
cin >> salary[i];
salary[i] *= 12;
cout <<"Yearly percentage raise (e.g 10% or 0%): ";
scanf("%f%%", &raise[i]);
salary[i] *= (((raise[i])/100.00) + 1);
puts("\n");
}
employee *employees = (employee*) malloc(sizeof(employee)*10);
for (int i = 0; i < n; i++)
{
employees[i] = employee(firstname[i], lastname[i], salary[i]);
}
cout << "TESING USING GET FUNCTIONS" << endl;
cout << "---------------------------\n\n";
for (int i = 0; i < n; i++)
{
cout << "Employee " <<i +1<< endl;
cout <<"-----------\n";
printf("First Name: %s", employees[i].getFirst().c_str());
printf("\nLast Name: %s",employees[i].getLast().c_str());
printf("\nYearly Salary: %d\n\n", employees[i].getSalary());
}
}
If you have an array of Employee instances and Employee is not POD (http://en.wikipedia.org/wiki/POD) you need to allocate memory from the stack using the operator new:
Employee* employees = new Employee[10];
And for having this working:
for (int i = 0; i < 10; i++)
{
employees[i] = Employee(firstname[i], lastname[i], age[i]);
}
you need to implement the operator= in your Employee class:
Employee& operator=(const Employee& src)
{
_firstname = src._firstname;
_lastname = src._lastname;
_age = src._age;
return *this;
}
If this looks like your Employee class:
class Employee
{
std::string first_name;
std::string last_name;
// other members and functions ...
};
Then using malloc() to create 10 of these is a complete and utter failure. The reason why is that yes, you allocated memory using malloc(), but that's all you did. You didn't construct 10 Employee objects. Those std::string members need to be constructed, not merely have memory allocated. So with that call to malloc() you have 10 fake Employees that were "created", and as soon as you attempt to do anything with one of them, then boom goes your program.
Do research on POD and non-POD types. You cannot treat non-POD types (as the class above is non-POD) as you would a POD type. For a non-POD type, the instance must be "officially" constructed, (the constructor must be invoked).
On the other hand, malloc() knows nothing concerning C++ and what is required to create an object correctly via construction. All malloc (and calloc, and realloc) knows is to allocate bytes and return a pointer to the allocated space.
Use a vector instead, it's resizable, it's easier to manage, and as Grady stated in his comment, it's also generally not good practice to use malloc in C++ code (although it's possible). Maybe do something that looks like this:
#include <vector>
...
int size = 10;
std::vector<Employee *> employees;
for(int i = 0; i < size; i++)
{
//as far as pulling in your data, that depends on where it's coming from
Employee *temp = new Employee(...);
employees.push_back(temp);
}
I'm rusty on my C++ but this should work.
Try this way:
#include <iostream>
class Employee
{
std::string m_firstname;
std::string m_lastname;
int m_age;
public:
Employee()
{
m_firstname=m_lastname="";
m_age=0;
}
void setFirstName(std::string firstname)
{
m_firstname=firstname;
}
void setLastName(std::string lastname)
{
m_lastname=lastname;
}
void setAge(int age)
{
m_age=age;
}
void displayEmp()
{
std::cout<<m_firstname;
std::cout<<m_lastname;
std::cout<<m_age;
}
};
int main()
{
std::string fname;
std::string lname;
int age;
Employee *employee = new Employee[10];
Employee *employeeptr=employee;
for(int i=0;i<10;i++)
{
std::cin>>fname;
std::cin>>lname;
std::cin>>age;
employeeptr->setFirstName(fname);
employeeptr->setLastName(lname);
employeeptr->setAge(age);
employeeptr++;
}
employeeptr=employee;
for(int i=0;i<10;i++)
{
employeeptr->displayEmp();
employeeptr++;
}
delete []employee;
return 0;
}
I'm just starting to learn object oriented programming in C++ and am having issues figuring out how to print an object that is stored inside an array. From what I know, I want to just try to try and go through the array and print out each employee object, how because objects are different than variables like int and double I'm sure it's causing a problem. Is my logic wrong, or is it just syntax? Here is my code:
Header:
#ifndef EMPLOYEE_H
#define EMPLOYEE_H
#include <string>
using namespace std;
class Employee
{
private:
string name;
string idNumber;
string department;
string position;
int yearsWorked;
public:
Employee();
Employee(string, string);
Employee(string, string, string, string, int);
void setName(string);
void setIdNumber(string);
void setDepartment(string);
void setPosition(string);
bool setYearsWorked(int);
string getName()const;
string getIdNumber()const;
string getDepartment()const;
string getPosition()const;
int getYearsWorked()const;
};
#endif
Implementation:
#include "Employee.h"
using namespace std;
Employee::Employee()
{
string name = "";
string idNumber = "";
string department = "";
string position = "";
int yearsWorked = 0;
}
Employee::Employee(string nm, string id)
{
string name = nm;
string idNumber = id;
string department = "";
string position = "";
int yearsWorked = 0;
}
Employee::Employee(string nm, string id, string dpt, string pos, int years)
{
string name = nm;
string idNumber = id;
string department = dpt;
string position = pos;
int yearsWorked = years;
}
void Employee::setName(string nm)
{
name = nm;
}
void Employee::setIdNumber(string id)
{
idNumber = id;
}
void Employee::setDepartment(string dpt)
{
department = dpt;
}
void Employee::setPosition(string pos)
{
position = pos;
}
bool Employee::setYearsWorked(int years)
{
if (years >= 0)
{
yearsWorked = years;
return true;
}
else
return false;
}
string Employee::getName()const
{
return name;
}
string Employee::getIdNumber()const
{
return idNumber;
}
string Employee::getDepartment()const
{
return department;
}
string Employee::getPosition()const
{
return position;
}
int Employee::getYearsWorked()const
{
return yearsWorked;
}
Main:
#include <iostream>
#include <iomanip>
#include "Employee.h"
using namespace std;
const int SIZE = 3;
int main()
{
Employee emp1("Jenny Jacobs", "JJ8990", "Accounting", "President", 15);
Employee emp2("Myron Smith", "MS7571", "IT", "Programmer", 5);
Employee emp3("Chris Raines", "CR6873", "Manufacturing", "Engineer", 30);
Employee employees[SIZE] = {emp1, emp2, emp3};
for (int i = 0; i < SIZE; i++)
{
cout << employees[i] << endl;
}
system("PAUSE");
return 0;
}
Add this:
std::ostream& operator<<( std::ostream& stream, Employee const& emp )
{
return (stream << emp.getName());
}
Modify as needed.
General comments:
Do not place using namespace std; in the global namespace in a header. Keep in mind that the standard library defines very common names like distance. Which can easily lead to name collisions.
Reserve ALL UPPERCASE names for macros, to reduce the chance of name collisions and inadvertent text substitution.
Preferentially pass potentially "large" objects, such as std::string, by reference, e.g. formal argument type std::string const&, in order to avoid excessive copying. There are some exceptions to this rule when one aims for perfect code, e.g. for C++11 move semantics, but it's a good general rule.
employees[i] is of type Employee. So either you have to print like
cout<<employees[i].getName(); // so on
Or you have to overload << operator for Employee type:
ostream& operator<<(ostream& stream, Employee const& emp );
Firstly. in my machine it compiles fine
Secondly, you are doing:
string name = nm;
So name is a automatic variable, Not the member of your class. You should do like:
name = nm; // if you delete int name; line
Or,
this->name = nm;
Some changes of your code:
Employee::Employee()
: yearsWorked( 0 )
{
}
Employee::Employee(string nm, string id)
: name( nm ), idNumber( id ), yearsWorked( 0 )
{
}
Employee::Employee(string nm, string id)
: name( nm ), idNumber( id ), department( dpt ), position( pos ), yearsWorked( years ),
{
}
std::ostream & operator <<( std::ostream &os, const Employee &emp )
{
return ( os << "ID: " << emp.idNumber << ", name: " << emp.name
<< ", department: " << emp.department << ", position: " << emp.position
<< ", years worked: " << emp.yearsWorked );
}
I want to use the C++ preprocessor to be able to write the following in any C++ block.
class Student {
private:
int age;
int grade;
int courses;
}
int main(){
CREATE_STUDENT 15+62+2 ;
}
The previous code will create a Student with these 3 members.
I want to use + operator overloading.
Any idea of how to do it?
I want EXACTLY the syntax I mentioned above.
Why not just use a constructor:
class Student {
private:
int age;
int grade;
int courses;
public:
Student(int a, int g, int c)
{
age = a;
grade = g;
courses = c;
}
}
int main(){
Student s(15,62,2);
}
Well, I completely fail to understand why you would want to do such a thing. But it is possible, sorta.
You'll need to make it a bit more complex than that to be able to use more than one such "construct" in the same block though.
#include <iostream>
#define GRADE_STUDENT Student student = (Student)
class Student {
public:
Student(int a): age(a), grade(-1), courses(-1), setup(0) {};
Student& operator+(int p)
{
switch(setup) {
case 0: grade = p; break;
case 1: courses = p; break;
default: /* die */ char *p=0; *p=0;
}
setup++;
return *this;
};
void print()
{
std::cout << age << ", " << grade << ", " << courses << std::endl;
};
private:
int age;
int grade;
int courses;
int setup;
};
int main()
{
{
GRADE_STUDENT 15+62+2 ;
student.print();
}
{
GRADE_STUDENT 15+62 ;
student.print();
}
{
GRADE_STUDENT 15+62+2+3 ; // crash
}
return 42;
}
You should template your class instead of working with the preprocessor.