c++无法从键盘输入tada
c++ can not input tada from keyboard
我是编程新手,我想知道如何从类中通过键盘输入数据。任何人
#include <iostream>
#include <string>
using namespace std;
class Human{
private:
string *name;
int *age;
public:
Human(string iname, int iage){
name = new string;
age = new int;
*name = iname;
*age = iage;
}
void display(){
cout << "Hi I am " << *name << " and I am " << *age << " years old" << endl;
}
~Human(){
delete name;
delete age;
cout << "Destructor!";
}
void input(string, int)
{
string name;
int age;
cout << "Name: "; cin >> name;
cout << "Age: "; cin >> age;
}
};
int main()
{
Human *d1 = new Human(Human::input(?????????????????));
d1->display();
delete d1;
return 0;
}
编辑:
我知道我能做什么:
int main()
{
Human *d1 = new Human("David",24);
d1->display();
return 0;
}
这个:
int main()
{
string name;
int age;
cout << "Name: "; cin >> name;
cout << "Age: "; cin >> age;
Human *d1 = new Human(name,age);
d1->display();
return 0;
}
但我想知道如何使用输入功能从键盘输入数据。
*
,是程序员可以使用的功能强大的东西,但只有在需要的时候才。在这种情况下,你不需要。你什么时候需要它们?我认为你应该把这件事留待以后讨论,并把重点放在我下面的例子上。当你明白了这一点,你可以在互联网上阅读Pointers。
#include <iostream>
#include <string>
using namespace std;
class Human {
private:
// data members of class
string name;
int age;
public:
// constructor without arguments
// useful for initializing the data members
// by an input function
Human() {
name = ""; // empty string
age = -1; // "empty" age
}
// constructor with arguments
// useful when you know the values
// of your arguments
Human(string arg_name, int arg_age) {
name = arg_name;
age = arg_age;
}
void display() {
cout << "Hi I am " << name << " and I am " << age << " years old"
<< endl;
}
// the data members will go out of scope automatically
// since we haven't used new anywhere
~Human() {
cout << "Destructor, but the default one would be OK too!n";
}
// prompt the user to giving values for name and age
void input() {
cout << "Please input name: ";
cin >> name;
cout << "Please input age: ";
cin >> age;
}
};
int main() {
// Let the user initialize the human
Human human_obj_i;
human_obj_i.input();
human_obj_i.display();
cout << "Now I am going to auto-initialize a humann";
// Let the program itseld initialize the human
Human human_obj("Samaras", 23);
human_obj.display();
return 0;
}
示例运行:
Please input name: Foo
Please input age: 4
Hi I am Foo and I am 4 years old
Now I am going to auto-initialize a human
Hi I am Samaras and I am 23 years old
Destructor, but the default one would be OK too!
Destructor, but the default one would be OK too!
希望能有所帮助!)
相关文章:
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 2D数组来自文本输入,中间有空格
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 检查输入是否不是整数或数字
- 正在尝试了解输入验证循环
- 读取文件并输入到矢量中
- C++如何通过用户输入删除列表元素
- 用c++从输入文件中读取另一行
- 读取文件的最后一行并输入到链接列表时出错
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何使用用户输入在C++中正确填充2D数组
- C++MySQL C api用户输入行
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- 用户定义函数中的指针和输入
- 如何在C++中检查2D数组中负值的输入验证
- 如何只允许用户输入正整数
- 在while循环中输入带有std::cin的字符串后,控制台会输出大量胡言乱语
- 输入中的字符串数未知(以字母表示)
- cpp二进制搜索问题,计算给定数组中输入元素的出现次数
- c++无法从键盘输入tada