需要帮助从类中调用函数

时间:2012-07-17 02:47:16

标签: c++ class function object if-statement

我无法从class OperateClass

中选择功能

它询问用户“你想要加,减,乘或除吗?我想:”(在主要部分)。不管我放什么,它都转到函数int add。我究竟做错了什么?

#include <iostream>

using namespace std;

int x = 1;
int number;
int total = 0;
int amt = 1;
int a;
int b;
int c;
int d;
string ans;

class OperateClass{
    public:
        int add(){
            while(x <= 2){
                cout << "Enter a number to use to add: " << endl;
                    cin >> a;
                total = total + a;
                x++;
                amt++;
            }
        }

        int subtract(){
            while(x <= 2){
                cout << "Enter a number to use to add: " << endl;
                    cin >> b;
                total = total - b;
                x++;
                amt++;
            }
        }

        int multiply(){
            while(x <= 2){
                cout << "Enter a number to use to add: " << endl;
                    cin >> c;
                total = total * c;
                x++;
                amt++;
            }
        }

        int divide(){
            while(x <= 2){
                cout << "Enter a number to use to add: " << endl;
                    cin >> d;
                total = total / d;
                x++;
                amt++;
            }
        }
};

int main()
{

cout << "Do you want to add, subtract, multiply or divide? I want to : " << endl;
cin >> ans;

if(ans == "add"){
OperateClass opOper;
opOper.add();
    }

else if (ans == "subtract"){
    OperateClass opOper;
    opOper.subtract();
    }

else if (ans == "multiply"){
    OperateClass opOper;
    opOper.multiply();
    }

else if(ans == "divide"){
    OperateClass opOper;
    opOper.divide();

    }

}

另外,这下面的功能是否足以打印?

void print(){
    cout << "Your total is: " << total << endl;  Where should I call this?

}

1 个答案:

答案 0 :(得分:2)

所有方法"Enter a number to use to add: "

都有相同的文字