我正在尝试获取类私有成员中变量的输入
I'm trying to get the input for variables in private members of a class
这是我的代码
#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 中也遇到了错误,在显示函数中也是如此...... 我知道要访问类的私有成员,我们必须在公共中创建一个函数,该函数将帮助我们间接访问...... 但是,我卡在最后几步。 知道如何解决这个问题的任何想法?
你可能想要这样的东西:
#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文章中找到有关此问题的详细信息。
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 内置函数可查看CPP中的成员变量
- 是否可以初始化不可复制类型的成员变量(或基类)
- 将包含C样式数组的对象初始化为成员变量(C++)
- 为什么我不能在一个类的不同行中声明和定义成员变量?
- 在循环中按顺序遍历成员变量
- c++类声明时,相同的例程,不同的成员变量类型
- 如何从另一个文件继承私有成员变量和公共函数
- 在C++类中,是否必须初始化作为数组的成员变量
- 如何从子成员函数修改父公共成员变量
- 我可以在 C++ 中将数据成员/变量从其定义之外添加到结构中吗?
- 从私有成员变量的成员方法返回unique_ptr
- 在派生类中使用基类的私有成员变量的最佳方法
- 静态 constexpr 类成员变量对多线程读取是否安全?
- C++:是否可以使用非静态成员变量模板?
- 打印所有继承的类成员变量和方法
- 如何在复杂继承中访问静态成员变量
- 为什么我不能在返回 const 的布尔函数中为类成员变量赋值?C++
- 成员变量与函数概念检查