【问题标题】:I'm trying to get the input for variables in private members of a class我正在尝试获取类私有成员中变量的输入
【发布时间】:2020-03-26 21:37:41
【问题描述】:

这是我的代码

#include <iostream>
#include <string>
using namespace std;

class Hamoud{
      private: 
      char name[50];
      int yearbirthday;

    public: 
        float tall;
        int age;
        void Getnameandyear(string name)
{
    std::array<char, 50> ;
    cout<<"enter your name: ";
    getline(nama);
    int year;
    year = yearbirthday;
    cout<<"enter your name: ";
    getchar(name);
    cout<<"Enter your year of birth";
    cin>>year;
}
    void display()
{
    cout<<"your name is: "<<name;
    cout<<"your year of birth is : "<<year;

}
};
int main ()
{
    Hamoud info;
    cout<<"enter your tall ";
    cin>>info.tall;
    cout<<"your tall is : "<<info.tall;
    cout<<"enter your age: ";
    cin>>info.age;
    cout<<"your age is: "<<info.age;
    info.Getnameandyear();
    info.display();

}

但我在函数 getnameandyear 中也遇到了错误,在显示函数中也是如此... 我知道要访问类的私有成员,我们必须在公共创建一个函数,这将帮助我们间接访问...... 但是,我被困在最后几个步骤.. 知道如何解决这个问题吗?

【问题讨论】:

  • nama[50] = name[50] 不会按照你的想法去做。它实际上是UB。更喜欢std::array&lt;char, 50&gt; 甚至std::string
  • 我试过 std::string 但也没用?
  • “我试过 std::string”:显示该代码,否则很难提供帮助。同时为两个不同的东西选择namaname 对代码的可读性没有帮助。
  • 请不要在 cmets 中发布代码,而是edit 问题。
  • 为什么函数Getnameandyear(string name) 需要一个参数?您正在使用它没有参数。

标签: c++ function class private public


【解决方案1】:

你可能想要这样的东西:

#include <iostream>
#include <string>
using namespace std;

class Hamoud {
private:
  string name;
  int yearbirthday;

public:
  float tall;
  int age;

  void Getnameandyear()
  {
    // no need for std::array<char, 50> or whatever here anyway
    cout << "enter your name: ";
    cin.ignore();   // this clears the input buffer. The exact reason why
                    // we need this is beyond your scope for the moment
    getline(cin, name);

    cout << "Enter your year of birth: ";
    cin >> yearbirthday;
  }

  void display()
  {
    cout << "your name is: " << name << "\n";
    cout << "your year of birth is: " << yearbirthday << "\n";
  }
};

int main()
{
  Hamoud info;
  cout << "enter your tall ";
  cin >> info.tall;
  cout << "your tall is: " << info.tall << "\n";
  cout << "enter your age: ";
  cin >> info.age;
  cout << "your age is: " << info.age << "\n";
  info.Getnameandyear();
  info.display();
}

但无论如何,我认为你应该开始阅读良好的初学者 C++ 教科书。

关于getline之前的cin.ignore();:具体原因暂时超出了您的范围,但您可以在此SO article中找到有关此问题的详细信息。

【讨论】:

    猜你喜欢
    • 2016-02-07
    • 2014-08-30
    • 1970-01-01
    • 1970-01-01
    • 2015-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多