Cin和cout在构造函数中

时间:2018-02-20 19:52:11

标签: c++ class constructor

我被告知从构造函数(家庭作业)中读取一个名称,但是类构造函数不应该采用任何参数 - 我发现这很奇怪。

我试图简单地将cout和cin.getline放在构造函数中,但这不起作用。我不知道如何在没有任何参数的构造函数中从用户读取数据。它甚至可能吗?

E.g

class Animal
{
  private:
    char name[20];

  public:
    Animal() { SOMEHOW READ NAME HERE WITHOUT CON. PARAMETER }
};

int main() {

  Animal a1; // should ask for name and read it, add it to data
  return 0;
}

2 个答案:

答案 0 :(得分:0)

#include  <iostream>
#include <sstream>

class Animal
{
public:
 Animal() : name()
{
    // Not the best design approach.Just show it possible for the question.
    std::cout << "Name of animal?" << std::endl;
    std::getline(std::cin, name);
    std::cout << name << std::endl;
}
private: 
   std::string name;
};

int main(int argc, char * argv[])
{
Animal a1; // should ask for name and read it, add it to data
return 0;
}

答案 1 :(得分:0)

我相信下面的代码是自我解释的,并附有评论以指导您。在面向对象中,类应包含setter和getter方法。我创建了一个包含一个私有字符串变量name的类name。在构造函数中,我要求一个名称并将其分配给正在创建的对象的name变量。然后,我使用名为getName()的方法显示#include <iostream> using namespace std; class Animal { private:string name; public: Animal() { cout<<"Enter the animal's name?"; getline(cin,this->name); //sets the current obj's name (storing the value) cout<<"The animal's name is "<<getName(); } public: string getName(){ return this->name; } //return current obj's name value (getter method) }; int main() { Animal a1; //cout<<a1.getName(); //it will get the name of a1's object return 0; } ,该方法返回当前对象的名称,它也称为getter方法。我相信你是面向对象的新手,我希望我能让你理解这些概念。

const rules = {
  start: 0,
  end: 5,
  tooltip: "Some note"
};
const Highlight = ({ words }) => {
  const portion = words.split(" ").slice(rules.start, rules.end).join(" ");
  const rest = words.split(" ").slice(rules.end).join(" ");

  return (
    <span>
      <span className="highlight">{portion}</span>
      <span className="standard">{rest}</span>
    </span>
  );
};
const App = () => {
  const sentence = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent tristique elit in volutpat iaculis.';
  
  return (
    <div>
      <Highlight words={sentence} />
     </div>
  )}
;

ReactDOM.render(<App />, document.getElementById("root"));