2016-12-24 114 views
-1

假设我想创建一个测验程序。我有一个抽象类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; 
} 
+0

请查看[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

+0

您可能能够直接访问父类数据成员,具体取决于父变量和继承访问的访问设置。 –

+0

不,你看到我想要将一个类(不继承)的值传递给另一个类 – Teeban

回答

0

只要QuestionMC类从类Question所有的Questionpublicprotected构件继承在QuestionMC的。

设置Questionfilename然后将其设置为QuestionMC成员因此将其添加到您的

void QuestionMC::setfilename(filename) 
{ 
    this->filename = filename; 
    mcfilename = filename; 
} 

它的工作原理,但一个问题:什么是遗产的目的是什么?只要基类中的成员filename为什么在派生类中再次声明它?

0

我对这个解决方案是创建一个存储指针,你使用 - 在你的情况下,一切三等功,它将存储:

的指针类球员。

指向类Question的指针,或者如果它是随后创建的,则指向包含所有问题指针的向量。

然后,您将该类的指针作为成员添加到这两个类(Player和Question),这将使他们能够访问彼此。

这个类将是一个全局变量,在程序结束之前不应该被删除(否则无论何时试图访问其他类会崩溃)。