假设我想创建一个测验程序。我有一个抽象类Question和它的一个名为QuestionMC的子类。然后我有Class播放器,它将从用户获得播放器信息,例如播放器名称和文件名(用于fstream)。我如何将类的播放器(文件名和播放器名称)的信息传递给类问题?C++将一个类的值传递给抽象类
class Question
{
public:
virtual void showQuestion()=0;
protected:
string filename;
string question;
string answer;
string questionType;
};
class Player
{
public:
Player(int score=0):score(score){}
void askdetails();
string getfilename();
string filename;
protected:
string fname;
string lname;
};
class QuestionMC:public Question
{
public:
void showQuestion();
void setfilename();
protected:
string mcQuestion;
string mcfilename;
};
int main()
{
Player p;
p.askdetails();
p.getfilename();
QuestionMC mc;
mc.setfilename(p.filename);
}
void Player::askdetails()
{
string filename,fname,lname;
cout << "Please enter your First name : ";
cin >> fname;
cout << "Please enter your last name : " ;
cin >> lname;
cout << "Please enter the filename your quiz is stored : " ;
cin >> filename;
ifstream infile;
infile.open(filename.c_str());
if (infile.fail())
{
cout << "Error Opening file, either file does not exist or invalid filename "<<endl;
exit(1);
}
this->fname=fname;
this->lname=lname;
this->filename=filename;
ofstream outfile;
outfile.open("Score.txt");
outfile << "Player name and score : " << fname <<" "<< lname << " "<< score<<endl ;
outfile.close();
}
string Player::getfilename()
{
return filename;
}
void QuestionMC::setfilename(filename)
{
mcfilename=filename;
}
请查看[The Definitive C++ Book Guide and List](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)。斯科特迈尔斯'特别有趣的。 – 2016-12-24 18:12:47
您可能能够直接访问父类数据成员,具体取决于父变量和继承访问的访问设置。 –
不,你看到我想要将一个类(不继承)的值传递给另一个类 – Teeban