如何从另一个类

时间:2016-06-12 03:52:58

标签: c++ string variables cout cin

你好我是c ​​++相对较新的我有一些java的经验和批量的很多但是我被困在如何从另一个类读取信息。

我想要做的是让我的主类包含故事和用户输入,但是将大多数变量存储在另一个类中,然后在所需的时间使用代码访问它们,例如:我有一部分代码用户输入他们的名字。我希望将输入存储为Variables类中的变量,然后当游戏说他们的名字(playerName)主类在Variables类中读取playerName然后在主类中显示它。那么我需要在主类中放置什么代码才能显示变量类

中的变量

2 个答案:

答案 0 :(得分:2)

// Demonstrates Variable class

#include <iostream.h>      // for cout

class Variables // begin declaration of the class
{
   private:  // begin.  private section
   std::string name; // member variable

   public:   // begin.    public section
     Variables();     // constructor
     std::string getName(); // accessor function
     void setName(int age);  // accessor function
 };

// constructor of Variables,
Variables::Variables()
{
     name = "";
}

// getName, Public accessor function:  
// returns value of name member
std::string Variables::getName() 
 return name;
}

// Definition of setName, public
// accessor function
void Variables::setName(std::string nme)
{
  // set member variable its age to
  // value passed in by parameter age
  name = nme;
}

int main()
{
  Variables variables(); //class object
  std::string name; //local variable

  std::cin >> name; 
  variables.setName(name); //set name

  std::cout << variables.getName();

  return 0;
}

对您需要的所有其他变量执行相同操作。有关更多信息,请查看此链接 www.java-samples.com/showtutorial.php?tutorialid=313"

答案 1 :(得分:0)

除了Twahanz的回答:如果你有一个Manager类在Variables保存数据时执行操作,那么同样有效。

class Manager {
  Variables m_my_data;
  ... void some_action();
}

void Manager::some_action() {
  std::cout << m_my_data.getName() << std::endl;
}

只是为了完整。