#include <iostream>
#include "people.h"
#include "birthday.h"
#include <string>
int main(){
std::string myname;
int a;
int b;
int c;
std::cout << " What is your name " << std::endl;
std::getline(std::cin, myname);
std::cout << "What month where you born " << std::endl;
std::cin >> a;
std::cout << "What day where you born " << std::endl;
std::cin >> b;
std::cout << "What year where you born in " << std::endl;
std::cin >> c;
birthday birthdayobjects(a ,b ,c);
people peopleobjects(myname, birthdayobjects);
peopleobjects.printInfo();
}
我有这样的main.cpp文件,其中有两个带有参数的构造函数,这些参数由用户输入。我想将此压缩为一个功能,以便主文件看起来像这样。
#include <iostream>
#include "people.h"
#include "birthday.h"
#include <string>
#include "askquestions.h"
int main(){
askquestions getquestions();
birthday birthdayobjects(a ,b ,c);
people peopleobjects(myname, birthdayobjects);
peopleobjects.printInfo();
}
但是问题是当我尝试这样做时,在该范围内看不到变量。如果将变量放在ask-questions类中,则依赖输入的main函数中的类将无法获取参数。我尝试了extern,但它已编译但无法正常工作。当我尝试在main.cpp文件中将变量设置为全局变量时,这也不起作用。在这种情况下最好的选择是什么?
答案 0 :(得分:0)
第一点
askquestions getquestions();
是错误的(它声明一个名为getquestions
的函数不是变量),应该是
askquestions getquestions;
像这样设计您的askquestions
类
class askquestions
{
public:
askquestions();
int geta() { return a; }
int getb() { return b; }
int getc() { return c; }
private:
int a;
int b;
int c;
};
这三个getX
方法称为 getters ,这是从类中获取信息的典型方式。
然后在您的主要功能中使用此类吸气剂
int main()
{
askquestions getquestions;
birthday birthdayobjects(getquestions.geta(), getquestions.getb(), getquestions.getc());
...
}
查看如何使用先前声明的getquestions
变量调用getter方法。
答案 1 :(得分:0)
askquestions
没有理由成为班级。为此,您应该更喜欢一个自由函数,该函数返回一个birthday
,或者最好返回一个people
例如
people askquestions()
{
std::string myname;
int month; // prefer descriptive names to single letters unless the single letter
// has a widely recognized meaning in the algorithm
int day;
int year;
std::cout << " What is your name " << std::endl;
std::getline(std::cin, myname);
std::cout << "What month where you born " << std::endl;
std::cin >> month;
std::cout << "What day where you born " << std::endl;
std::cin >> day;
std::cout << "What year where you born in " << std::endl;
std::cin >> year;
return people(myname, birthday (month ,day , year));
}
用法:
int main(){
people peopleobjects = getquestions();
peopleobjects.printInfo();
}