新的c ++,需要OOP技巧

时间:2014-07-10 08:54:14

标签: c++

我只是想说这是我第一次尝试学习编程语言,这样可以免除我的冷漠。我正在尝试习惯面向对象的编程。问题是我无法弄清楚如何获得用户输入的内容而不将其存储在公共变量中。

#include <iostream>
using namespace std;

class Aclass{
public:
    void setx(int a){
        x = a;
    }
    void sety(int b){
        y = b;
    }
    void setsum(int c){
        c = sum;
    }
    int getx(){
        return x;
    }
    int gety(){
        return y;
    }
    int getsum(){
        return sum;
    }

private:
    int x;
    int y;
    int sum;
    int diff;
    int mult;
    int div;
};

int main()
{
    string NB;
    cout << "What you like to do ?(Sum, Difference, Multiplication or Division)\n";
    cin >> NB;

    if(NB == "Sum") {
        Aclass Ab;
        cout << "Enter Your First Number\n";
        Ab.setx(cin >> a);
        return 0;
    }
}

1 个答案:

答案 0 :(得分:3)

您需要将用户输入存储在变量中,然后将其传递给Ab.setx以将变量存储在对象中,即

int main() {
    // Declare your variables
    Aclass Ab;
    string choice;
    int x, y;

    // Get user choice
    cout << "What you like to do? (Sum, Diff, Mul or Div)" << endl;
    cin >> choice;

    // Get user inputs
    if (choice == "Sum") {
        cout << "Enter your first number" << endl;
        cin >> x;           // Get the user input from 'cin' and store it in 'a'
        cout << "Enter your second number" << endl;
        cin >> y;

        // Pass x, y to the Ab object and store them there
        Ab.setx(x);
        Ab.sety(y);

        cout << "The final sum is: " << Ab.getsum() << endl;
    }

    return 0;
}

注意:上面的代码需要getsum的实现,如下所示:

class Aclass{
// ...
public:
    int getsum(){
        return (this->x + this->y);
    }
// ...
相关问题