我有一個C++的作業,要求我創建一個名爲Tips
類,即:變量是不確定的,但在我的構造函數C++明確
- 只有一個成員變量,
float taxRate
- 有兩個構造,默認設置
taxRate
到.65
,以及一個參數構造函數,它將taxRate
設置爲用戶在我的tipMain.cpp
文件中輸入的任何浮點數。 - 只有一個功能,
computeTip
,其接受兩個參數:totBill
和tipRate
,既float
是一個必須計算稅前用餐的費用和返回基於該值和所需的尖端速度尖端。
我試圖在computeTip函數中使用taxRate時出現我的問題。
如果我使用taxRate
,computeTip
不明白的taxRate
值,說明它是不確定的,即使我不指定tips::taxRate
,之前我甚至編譯Visual Studio的狀態
Error: a nonstatic member reference must be relative to a specific object.
我隱約明白這一點錯誤,但即使我聲明taxRate
在我的.h文件中是靜態的,我也會得到LNK2019錯誤。
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
和我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;
}
謝謝你和所有那些下面你!我知道這會很簡單。我發誓我不是特別的。 – user3042535