I have a C++ assignment that requires me to create a class called Tips
, that:
- has a single member variable,
float taxRate
- has two constructors, a default that sets
taxRate
to.65
, and a one parameter constructor, that setstaxRate
to whatever float the user enters in mytipMain.cpp
file. - has only one function,
computeTip
, that accepts two arguments:totBill
andtipRate
, bothfloat
s that must calculate the before-tax meal cost, and return the tip based on that value and the desired tip rate.
My issue occurs when I attempt to use taxRate inside the computeTip function.
If I use taxRate
, computeTip
doesn't understand the value of taxRate
, stating it is undefined, and even if I do specify tips::taxRate
, before I even compile Visual Studio states
Error: a nonstatic member reference must be relative to a specific object.
I vaguely understand this error, but even if I declare taxRate
to be static in my .h file, I get LNK2019 errors.
Tips.cpp
#include <iostream>
#include <float.h>
#include "Tips.h"
using namespace std;
Tips::Tips()
{
taxRate = 0.65;
}
Tips::Tips(float a)
{
taxRate = a;
}
float computeTip(float totBill, float tipRate)
{
float mealOnly = 0;
mealOnly = (totBill/taxRate); //written both ways to show errors. taxRate undefined here.
mealOnly = (totBill/Tips::taxRate); //Error: a nonstatic member reference must be relative to a specific object
return (mealOnly * tipRate);
}
Tips.h
#ifndef Tips_H
#define Tips_H
#include <float.h>
using namespace std;
class Tips
{
public:
Tips();
Tips(float);
float computeTip(float, float, float);
float taxRate;
};
#endif
and my tipMain.cpp
#include "Tips.h"
#include <iostream>
#include <iomanip>
using namespace std;
float tax;
float meal;
float tip;
void tipProcessor();
int main()
{
char entry;
int toggle = 1;
cout << "Welcome to the Gratuity Calculator!" << endl;
cout << endl;
while (toggle != 0)
{
cout << "Enter 1 to calculate tip." << endl;
cout << endl;
cout << "Enter 2 to exit." << endl;
cout << endl;
cout << "Entry: ";
cin >> entry;
switch (entry)
{
case '1':
tipProcessor();
break;
case '2':
toggle = 0;
break;
default:
cout << "Enter 1 or 2." << endl;
cout << endl;
break;
}
}
system("pause");
return 0;
}
void tipProcessor()
{
cout << "Enter bill total: ";
cin >> meal;
cout << endl;
cout << "Enter tax rate: ";
cin >> tax;
cout << endl;
Tips thisTip(tax);
cout << "Enter tip percent: ";
cin >> tip;
cout << endl;
cout << "Tip is $" << setprecision(4) << thisTip.computeTip(meal, tip, thisTip.taxRate) << "." << endl;
cout << endl;
}