Fuction-definition not allowed RetailItem - c++

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.

Related

Identifier not found - error C3861 in Visual Studio 2019

I have a problem with my code. Unfortunately, when compiling I get these errors all the time. What can this be caused by and how to fix it?
error C3861: 'print': identifier not found
My code:
main.cpp
#include "pojazdy.h"
#include <iostream>
using namespace std;
int main()
{
Pojazdy** poj;
int size{ 0 }, index{ 0 };
Petla(poj, size);
print(poj, size);
wyrejestruj(poj,size,0);
print(poj, size);
wyrejestruj(poj,size);
return 0;
}
pojazdy.h
#ifndef pojazdy_h
#define pojazdy_h
#include <iostream>
#include <cstdlib>
using namespace std;
class Pojazdy
{
public:
string typ;
string marka;
string model;
string z_dod;
int ilosc;
int cena;
void dodaj();
void d_pojazd(Pojazdy**& pojazdy, int& size);
void wyrejestruj(Pojazdy**& pojazdy, int& size, int index);
void print(Pojazdy** pojazdy, int size);
void Petla(Pojazdy**& p, int& size);
//void wyswietl();
int get_ilosc() { return ilosc; }
string get_typ() { return typ; }
string get_marka() { return marka; }
string get_model() { return model; }
int get_cena() { return cena; }
void set_ilosc(int x);
};
#endif
pojazdy.cpp
#include "pojazdy.h"
#include <iostream>
using namespace std;
void Pojazdy::set_ilosc(int x) { ilosc = x; }
void Pojazdy::dodaj()
{
cout << "DODAWANIE POJAZDU..." << endl;
cout << "Podaj typ pojazdu:";
cin >> typ;
cout << "Podaj marke pojazdu: ";
cin >> marka;
cout << "Podaj model pojazdu: ";
cin >> model;
cout << "Dodaj cene pojazdu: ";
cin >> cena;
}
void Petla(Pojazdy**& p, int& size) {
char z_dod;// = 'N';
do {
d_pojazd(p, size); //odpowiada za dodawnie
p[size - 1]->dodaj();
cout << "Czy chcesz zakonczyc dodawanie? Jesli tak, wcisnij Y/N: ";
cin >> z_dod;
} while (z_dod == 'N' || z_dod == 'n');//while (p[size]->z_dod == "N" ||p[size]->z_dod == "n");
}
void print(Pojazdy** pojazdy, int size) {
std::cout << "====================================" << std::endl;
for (int i{ 0 }; i < size; i++)
std::cout << "Typ: " << pojazdy[i]->get_typ() << " Marka: " << pojazdy[i]->get_marka() << " Model: " << pojazdy[i]->get_model() << " Cena: " << pojazdy[i]->get_model() << std::endl;
}
void wyrejestruj(Pojazdy**& pojazdy, int& size) {
for (size_t i{ 0 }; i < size; i++)
delete pojazdy[i];
delete[] pojazdy;
size = 0;
pojazdy = NULL;
}
void wyrejestruj(Pojazdy**& pojazdy, int& size, int index) {
if (index < size) {
Pojazdy** temp = new Pojazdy * [size - 1];
short int j{ -1 };
for (size_t i{ 0 }; i < size; i++) {
if (i != index) {
j++;
temp[j] = pojazdy[i];
}
}
delete[] pojazdy;
--size;
pojazdy = temp;
}
else
std::cout << "Pamiec zwolniona!" << std::endl;
}
void d_pojazd(Pojazdy**& pojazdy, int& size) {
Pojazdy** temp = new Pojazdy * [size + 1];
if (size == 0)
temp[size] = new Pojazdy;
else {
for (int i{ 0 }; i < size; i++)
temp[i] = pojazdy[i];
delete[] pojazdy;
temp[size] = new Pojazdy;
}
++size;
pojazdy = temp;
}
I used #ifndef, #define, #endif and #pragma once, but none of them work. I will be really grateful for every code, I am already tired of this second hour. And forgive the non-English variables and function names for them - it's university code, so I didn't feel the need.
Move the functions below outside the class declaration.
void wyrejestruj(Pojazdy**& pojazdy, int& size, int index);
void print(Pojazdy** pojazdy, int size);
void Petla(Pojazdy**& p, int& size);
Or make them static and call like Pojazdy::print(poj, size);.
You declared a non-static member function print in the class definition
class Pojazdy
{
public:
// ...
void print(Pojazdy** pojazdy, int size);
//...
but you are trying to call it as a stand-alone function in main
print(poj, size);
So the compiler issues an error.
The declaration of the function as a stand alone function that at the same time is its definition in the file pojazdy.cpp is not visible in the module with main because this module includes only the header with the class declaration.
You should decide whether this function should be a member function of the class or a stand alone function.
You are not calling your member functions correctly. print can only be called on an object of type Pojazdy, so you need to do something like:
Pojazdy** poj;
int size{ 0 }, index{ 0 };
Pojazdy x; // Creates an object of Pojazdy called z
x.print(poj,size); // Calls the print method on x
Alternatively, if you don't want to have to declare an object, you could make the method static and just call it on the class.
In the .h file:
static void print(Pojazdy** pojazdy, int size);
And then in main:
Pojazdy** poj;
int size{ 0 }, index{ 0 };
Pojazdy::print(poj, size); // Calls the print method on the class
You put your function prototypes in the wrong place. They should be after the class decalration.
class Pojazdy
{
...
};
void print(Pojazdy** pojazdy, int size);
void wyrejestruj(Pojazdy**& pojazdy, int& size);
etc.
print is not a member of the Pojazdy class, so it's wrong to put the prototype inside the Pojazdy class declaration.

multiple inheritance variables returning correctly

I'm working on a multiple inheritance exercise and I'm running into a strange error. My code is not returning the correct information to the console. It is just outputting zero, I have checked multiple times in my code and I can't seem to find anything obviously wrong. I'm fairly new to C++ so any help I would appreciate it, in addition to any other critique.
The console will output
Maverick
South station
50 - passengers, is ok
40 - speed
0 - it is supposed to take distance/mph and output 2.6 in this case, but is returning nothing.
MBTA.cpp
#include "MBTA.h"
//objects
transportation Dest;
MBTA::MBTA()
{
}
MBTA::MBTA(string strIn, string strInTransport, int iIn, int distIn, int eIn)
{
setTrain(strIn);
//Destination
Dest.setTransport(strInTransport);
//set passengers
setPass(iIn);
Dest.setMilesToDest(distIn);
engine.setMPH(eIn);
//outputs train information
printTrainDestinationHours();
//used printf as I was running into issue with using cout here
//cout << " I am going to ";
printf("I am going to %s\n", Dest.getTransport().c_str());
//uses engine stats function
cout << "I go " << engine.getMPH() << endl;
printf("It will take me %.2f hours to arrive", redline.getTotal());
}
void MBTA::setTravelDist(int iIn)
{
double destdistance = Dest.getDist();
double trainMPH = engine.getMPH();
//this divides miles by MPH, this might return a float
redline.setTotal(50, 10);
}
MBTA::~MBTA()
{
}
MBTA.H
#pragma once
#include "train.h"
class MBTA :
public train
{
public:
engine engine;
train redline;
MBTA();
//train, destination, passengers, traveldist, speed
MBTA(string, string, int, int, int);
void setTravelDist(int);
//double getTotal();
//uses engine stats function
//double total = 0;
~MBTA();
};
Train.cpp
#include "train.h"
#include <iostream>
#include <cstdio>
#include <cmath>
using std::string;
using std::cout;
using std::endl;
//object member for transport
transportation tTrain;
train::train()
{
}
void train::printTrainDestinationHours()
{
printf("\n\nTrain type: %s\n", getTrain().c_str());
//passengers
printf("I have %d passengers\n", getPass());
}
void train::setPass(int iIn)
{
passengers = iIn;
}
int train::getPass()
{
return passengers;
}
void train::setTrain(string strIn)
{
trainName = strIn;
}
string train::getTrain()
{
return trainName;
}
void train::setTotal(int aIn, int bIn)
{
//dist / mph
total = aIn / bIn;
}
double train::getTotal()
{
return total;
}
train::~train()
{
}
Train Header
#pragma once
#include <iostream>
#include <cstdio>
using std::string;
using std::cout;
using std::endl;
#include "engine.h"
#include "transportation.h"
class train : public transportation
{
public:
train();
void printTrainDestinationHours();
//set and get destination
//num of pass
void setPass(int);
int getPass();
//train
void setTrain(string);
string getTrain();
//distance
void setTotal(int, int);
double getTotal();
~train();
private:
engine engineStats;
int total = 0;
string trainName = "";
string destination = "";
int passengers = 0;
};
engine.cpp
#include "engine.h"
engine::engine()
{
}
void engine::setMPH(int iIn)
{
MPH = iIn;
}
int engine::getMPH()
{
return MPH;
}
engine::~engine()
{
}
engine header
#pragma once
class engine
{
public:
engine();
//return
void setMPH(int);
int getMPH();
~engine();
protected:
int MPH = 0;
};
'''
transportation cpp
'''
#pragma once
class engine
{
public:
engine();
//return
void setMPH(int);
int getMPH();
~engine();
protected:
int MPH = 0;
};
transportation header
#include "transportation.h"
transportation::transportation()
{
}
void transportation::setTransport(string strIn)
{
destination = strIn;
}
string transportation::getTransport()
{
return destination;
}
void transportation::setMilesToDest(int iIn)
{
MilesToDestination = iIn;
}
int transportation::getDist()
{
return MilesToDestination;
}
transportation::~transportation()
{
}
main file
#include <iostream>
using std::string;
using std::cout;
using std::endl;
using std::cin; //for ignore
#include "challenger.h"
#include "MBTA.h"
#include "plane.h"
int main()
{
//object composition of vehicle type
// vehicle type location, passengers, MPH , distance
challenger SRT8707("Boston", 2, 100, 200);
plane boeing("boeing", "houston", 50, 500, 300);
MBTA redline("Maverick", "South station", 50, 100, 40);
//pause and blank line
cout << endl << endl;
cin.ignore();
}

Getting values from a vector of object pointers

I need to write the name, act# balance and address of the object that is stored in the vector, to a file.
I believe I have the program to push the objects into the vectors, but since they are vectors of object pointers I am having problems figure out how to call the object and print all 3 objects out.
Main.cpp
vector<Account*> accounts;
accounts.push_back(new Savings(new Person("Bilbo Baggins", "43 Bag End"), 1, 500, 0.075));
accounts.push_back(new Checking(new Person("Wizard Gandalf", "Crystal Palace"), 2, 1000.00, 2.00));
accounts.push_back(new Savings(new Person("Elf Elrond", "Rivendell"), 3, 1200, 0.050));
ofstream outFile;
outFile.open("accounts.txt");
if (outFile.fail())
{
cout << "\nYour file did not open, the program will now close!\n";
system("PAUSE");
return 0;
}
else
{
cout << "\nBINGO!!! It worked.\n\n";
system("PAUSE");
cout << "\n";
}
// New : Using a loop, send messages to each of the three Account objects to write themselves out to the file.
cout << "\nNow we are going to write the information to \"Accounts.txt\" \n\n";
system("PAUSE");
for (int i = 0; i < accounts.size(); i++) {
accounts[i]->writeAccount(outFile);
}
Account.h
#pragma once
#include <string>
#include <iostream>
#include "Person.h"
using namespace std;
// Account class - abstract/parent class
class Account
{
private:
int actNumber;
double actBallance;
Person PersonName;
public:
Account();
Account(int, double, Person*);
int getActNumber();
virtual double getActBallance();
string getName();
string getAdd();
void deposit(double);
void withdrawl(double);
virtual void writeAccount(ofstream&);
virtual void readAccount(ifstream&);
void testAccount(int i);
};
// Checking class: inherits from the Account class
class Checking : public Account
{
private:
double monthlyFee;
public:
Checking();
Checking(Person*, int, double, double);
void setMonthlyFee(double);
double getActBallance();
void writeAccount(ofstream&);
void readAccount(ifstream&);
};
// Savings class: inherits from the Account class
class Savings : public Account
{
private:
int interestRate;
public:
Savings();
Savings(Person*, int, double, double); // person, act#, Ballance, Interest Rate
void setInterestRate(double);
double getActBallance();
void writeAccount(ofstream&);
void readAccount(ifstream&);
};
Account.cpp
#include "Account.h"
#include <string>
using namespace std;
Account::Account()
{
actNumber = 0;
actBallance = 0.0;
}
Account::Account(int act, double bal, Person* name)
{
actNumber = act;
actBallance = bal;
}
int Account::getActNumber()
{
return actNumber;
}
double Account::getActBallance()
{
return actBallance;
}
string Account::getName()
{
return PersonName.getName();
}
string Account::getAdd()
{
return PersonName.getAddress();
}
void Account::deposit(double money)
{
actBallance += money;
}
void Account::withdrawl(double money)
{
actBallance -= money;
}
void Account::writeAccount(ofstream& output)
{
output << actNumber << "\n" << actBallance << "\n" << PersonName.getName() << "\n" << PersonName.getAddress() << endl;
}
void Account::readAccount(ifstream& output)
{
output >> actNumber;
output >> actBallance;
}
// Checking Account
Checking::Checking() {
monthlyFee = 0;
}
Checking::Checking(Person* per, int actNum, double bal, double interest) {
bal -= monthlyFee;
Account:Account(actNum, bal, per);
}
void Checking::setMonthlyFee(double fee) {
monthlyFee = fee;
}
double Checking::getActBallance() {
double ballance = Account::getActBallance();
return ballance = monthlyFee;
}
void Checking::readAccount(ifstream& output) {
int actNumber = Account::getActNumber();
int actBallance = Account::getActBallance() - monthlyFee;
output >> actNumber;
output >> actBallance;
}
void Checking::writeAccount(ofstream& output) {
int actNumber = Account::getActNumber();
int actBallance = Account::getActBallance();
output << actNumber << "\n" << actBallance << endl;
}
// Savings Account
Savings::Savings() {
interestRate = 0;
}
// Savings(Person, int, double, double) // person, act#, Ballance, Interest Rate
Savings::Savings(Person* per, int actNum, double bal, double interest) {
bal += (bal * interest);
Account:Account(actNum, bal, per);
}
void Savings::setInterestRate(double rate) {
interestRate = rate;
}
double Savings::getActBallance() {
double ballance = Account::getActBallance();
return ballance + (ballance * interestRate);
}
void Savings::readAccount(ifstream& output) {
double actBallance = Account::getActBallance();
int actNumber = Account::getActNumber();
actBallance += (actBallance * interestRate);
output >> actNumber;
output >> actBallance;
}
void Savings::writeAccount(ofstream& output) {
int actNumber = Account::getActNumber();
int actBallance = Account::getActBallance();
output << actNumber << "\n" << actBallance << endl;
}
I realize I am so far off... but I have been at this for HOURS and I can not figure out for the life of me, but to take the vector of object pointers and output the objects values.
Person.h
#pragma once
#include <string>
#include <fstream>
using namespace std;
class Person
{
private:
string name;
string address;
public:
Person();
Person(string a, string b);
string getName();
string getAddress();
void writePerson(ofstream&);
void readPerson(ifstream&);
};
Person.cpp
#include "Person.h"
#include <string>
using namespace std;
Person::Person()
{
name = "NAME";
address = "123 STREET";
}
Person::Person(string a, string b)
{
name = a;
address = b;
}
string Person::getName()
{
return name;
}
string Person::getAddress()
{
return address;
}
void Person::writePerson(ofstream& output)
{
output << name << " " << address << endl;
}
void Person::readPerson(ifstream& output)
{
output >> name;
output >> address;
Person(name, address);
}
Read again your course books on constructors: there are severe issues in all of your constructors. As a result, you don't initialize the object member variables, and you effectively end up printing lots of zeros and empty strings...
Firstly, for your base-class, you must initialize the person name. You should have written:
Account::Account(int act, double bal, Person* name)
: actNumber(act)
, actBallance(bal)
, PersonName(name)
{}
Secondly, for your derived classes, the initialisation of the base-class must be done in the initializer-list, not in the body of the ctor. Here is for exemple the correct definition for the Checking's ctor:
Checking::Checking(Person* per, int actNum, double bal, double interest)
: Account(actNum, bal, per)
, monthlyFee(-bal)
{}
Thirdly, be careful to initialize the member variables with the arguments of the ctor. You sometimes do the opposite and assign the ctor arguments with the (uninitialized) member variables.
BTW, Account is a base-class for a polymorphic hierarchy: thus, the Account destructor must be declared virtual.

Classes in C++: Declaring an Instance

I have consulted many websites but have not successfully completed my code.
I am trying to write some code that spits out information about a car, once the user provides information. After compiling, the compiler says that "declaration does not declare anything." Here's the code:
#include <iostream>
#include <string>
#include "Car.h"
using namespace std;
Car::Car()
{
}
void Car::accel()
{
speed += 5;
}
void Car::brake()
{
speed -= 5;
}
void Car::setSpeed(int newSpeed)
{
speed = newSpeed;
}
int Car::getSpeed()
{
return speed;
}
void Car::setMake(string newMake)
{
make = newMake;
}
string Car::getMake()
{
return make;
}
void Car::setYearModel(int newYearModel)
{
yearModel = newYearModel;
}
int Car::getYearModel()
{
return yearModel;
}
int main()
{
Car auto; //instance of class Car
int autoYear; //year of auto
string autoMake; //make of auto
int autoSpeed; //speed of auto
cout << "Enter the year model of your car. ";
cin >> autoYear;
cout << "Enter the make of your car. ";
cin >> autoMake;
auto.setYear(autoYear); //stores input year
auto.setMake(autoMake); //stores input make
}
And the header, Car.h:
#include <iostream>
#include <string>
using namespace std;
#ifndef CAR_H
#define CAR_H
class Car
{
private:
int yearModel;
string make;
int speed;
public:
Car();
void accel();
void brake();
void setSpeed(int newSpeed);
int getSpeed();
void setMake(string newMake);
string getMake();
void setYearModel(int newYearModel);
int getYearModel();
};
#endif
I also have errors for missing semicolons every time my object auto appears ("expected ; before auto" and "expected primary-expression before auto"). What could be the problem?
auto is a keyword. You'll need to pick a different name.

Unable to remove missing ; before variable name error

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