我是编程新手,我想知道如何从课堂键盘输入数据。任何人?
#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;
}
但我想知道如何通过输入功能从键盘输入数据。
答案 0 :(得分:0)
Zygis你需要阅读C ++基础知识的教程。指针*
是程序员可以使用的强大功能,但只在需要时 。在这种情况下,您不需要。你什么时候需要它们?我想你应该留待以后再关注下面我的例子。当您了解这一点时,您可以在互联网上阅读有关指针的信息。
#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 human\n";
// 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!
希望有所帮助! ;)