解释为什么类不存储和打印输入的值

时间:2015-12-06 23:27:50

标签: c++ string function class setter

我是新手,我必须在一个类中编写我自己的函数和变量,该类在输入时存储流动站信息,并且出于某种原因,每当我编写我的函数并尝试在main中调用它们时它们都不起作用。我提供了我的代码,我想知道是否有人可以帮我解释如何为每个流动站r1-r5存储流动站数据。谢谢。

class Rover{

private:

    string name;
    int xpos;
    int ypos;
    string direction; //Use Cardinal Directions (N,S,E,W)
    int speed; //(0-5 m/sec)
    public:
    //Constructors
    //defaultRover();
    //Rover();
//Get functions
string getName();
int getXpos();
int getYpos();
string getDirect();
int getSpeed();
void getRoverData();

//Set functions
string setName();
void setXpos();
void setYpos();
void setDirect();
void setSpeed();
};
//Constructor function
/*Rover::defaultRover()
{
    xpos=0;
    ypos=0;
    direction="N";
    speed=0;
}
*/
/*
   Rover::Rover()
   {
       cout<<"Please enter the starting X-position: ";
       cin>>xpos;
       cout<<"Please enter the starting Y-position: ";
       cin>>ypos;
       cout<<"Please enter the starting direction (N,S,E,W): ";
       cin>>direction;
       cout<<"Please enter the starting speed (0-5): ";
       cin>>speed;

       cout<<endl;
   }
*/
//Getter functions
string Rover::getName()
{
    return name;
}

int Rover::getXpos()
{
    return xpos;
}

int Rover::getYpos()
{
    return ypos;
}

string Rover::getDirect()
{
    return direction;
}

int Rover::getSpeed()
{
    return speed;
}

void Rover::getRoverData()
{
    cout<<name;
    cout<<xpos;
    cout<<ypos;
    cout<<direction;
    cout<<speed;
}

//Setter functions
string Rover::setName()
{
    cout<<"Please enter the Rover name ";
    cin>>name;

}

void Rover::setXpos()
{
    cout<<"Please enter the X-position of the Rover ";
    cin>>xpos;
}

void Rover::setYpos()
{
    cout<<"Please enter the Y-position of the Rover ";
    cin>>ypos;
}

void Rover::setDirect()
{
    cout<<"Please enter the direction of the Rover (N,S,E,W) ";
    cin>>direction;
}

void Rover::setSpeed()
{
    cout<<"Please enter the speed of the Rover (0-5) ";
    cin>>speed;
}


int main(int argc, char** argv)
{

    Rover r1, r2, r3, r4, r5;

    r1.setName();
    r1.getName();

    return 0;
}

1 个答案:

答案 0 :(得分:0)

作为一般规则......

getter和setter不应与stdin或stdout

通信
  • 吸气者应该return他们得到什么
  • setters应该将成员分配给传递的内容

让我们假装上课Foo

class Foo {
  public:  
      // setters
      void set_bar(int bar) { bar_ = bar; }
      void set_baz(std::string baz) { baz_ = baz; }
      void set_boo(double boo) { boo_ = boo; }
      // getters
      int get_bar() const { return bar_; }
      std::string get_baz() const { return baz_; }
      double get_boo() const { return boo_; }
  private:
    int bar_;
    std::string baz_;
    double boo_;
};

应该使用的方式是这样的:

Foo foo;
int bar;
std::cout << "Please enter bar: " << std::endl;
std::cin >> bar;
foo.set_bar(bar);
std::cout << "foo's bar is " << foo.get_bar() << std::endl;

你需要更改很多代码,但我希望这会有所帮助。