标题或主文件中的循环

时间:2017-02-24 02:50:28

标签: c++ header

所以我在我的头文件中放了一个while循环,我想将它连接到我的main.cpp,但是我的main.cpp没有播放它,除非它在我的头文件中说明。所以我想知道标题中是否有一个while循环甚至是必要的?该任务是创建一个程序,根据她的销售额计算用户的工资。

这是我的头文件:

class Salary
{
public:
Salary(){};
    Salary(double employeeSales, double employeeSalary)
    :sales{employeeSales},salary(employeeSalary)
    {
        while(employeeSales != -1)
        {
            salary = 200 + (.09 * sales);
        }
    }
void setSales(double employeeSales)
{
    sales = employeeSales;
}
void setSalary(double employeeSalary)
{
    salary = employeeSalary;
}

double getSales() const{return sales;}
double getSalary() const{return salary;}
private:
    double sales;
    double salary;
};

这是我的main.cpp

#include <iostream>
#include <iomanip>
#include "Salary.h"

using namespace std;
int main()
{
    Salary mySalary;
    double employeeSales;
    double employeeSalary;
    cout << fixed << setprecision(2);
    cout << "Enter sales in dollars(-1 to quit): ";
    cin >> employeeSales;
    mySalary.setSales(employeeSales);

    while(true)
    {
        employeeSalary = 200 + (.09 * employeeSales);
        mySalary.setSalary(employeeSalary);
        cout << "Salary is: $" << mySalary.getSalary();
        cout << "Enter sales in dollars(-1 to quit): ";
        cin >> employeeSales;
        mySalary.setSales(employeeSales);
    }

}

然而,主要的while循环赢了,除非我把while(employeeSales!= -1)

1 个答案:

答案 0 :(得分:0)

不要让你的构造函数处理垃圾数据(-1作为参数),只需在main中的while循环中创建一个if语句,如果用户输入-1就会中断。

while(true)
{
    employeeSalary = 200 + (.09 * employeeSales);
    mySalary.setSalary(employeeSalary);
    cout << "Salary is: $" << mySalary.getSalary();
    cout << "Enter sales in dollars(-1 to quit): ";
    cin >> employeeSales;
    if( employeeSales == -1)
    {
        cout << "Stopping program!" << endl;
        break; // exits the while loop
    }
    mySalary.setSales(employeeSales);
}

这样做可以使Salary构造函数中的while循环变得不必要,并且应该有希望解决您的问题。