2017-05-30 92 views
-8

我真的希望你們都能幫助我解決這個問題。我既是該網站的新手,也是C++的新手(僅學習了大約一個月)。我的編譯器是VS2012。我正在爲一個程序設置一組菜單。菜單爲每個類使用簡單的switch語句。每個菜單都來自基本菜單類。由於我似乎沒有遇到菜單類本身的問題,因此我現在不包括它們,因爲它們全都在具有自己的.h頭文件的獨立.cpp文件中。我包含基本菜單.cpp和.h文件,因爲我相信它們是我的問題的一部分。我也包括我的主要.cpp文件。錯誤C2440:'初始化':無法從'BaseMenu'轉換爲'BaseMenu *'

BaseMenu.h

#ifndef BaseMenu_M 
    #define BaseMenu_M 


    #include<string> 
    #include<iostream> 



    using std::cout; 


    class BaseMenu 
    { 
    public: 

     BaseMenu() { m_MenuText = "This is where the menu text choices will appear"; }// Constructor providing menu text to each derived menu 
     virtual ~BaseMenu() { }    // virtual destructor 
     virtual BaseMenu getNextMenu(int iChoice, bool& iIsQuitOptionSelected);   // used to set up the framework 
     virtual void printText()                 // member function to display the menu text 
     { 
      cout << m_MenuText << std::endl; 
     } 

    protected: 
     std::string m_MenuText;  // string will be shared by all derived classes 
    }; 

    #endif 

BaseMenu.cpp

#include "stdafx.h" 
    #include "BaseMenu.h" 
    #include<iostream> 


    BaseMenu::BaseMenu(void) 
    { 
    } 


    BaseMenu::~BaseMenu(void) 
    { 
    } 

主要.cpp文件

#include "stdafx.h" 
    #include "BaseMenu.h" 
    #include "TicketSalesMenu.h" 
    #include "MainMenu.h" 
    #include "ListMenu.h" 
    #include "AdministrativeTasksMenu.h" 
    #include "basemenu.h" 


    #include <iostream> 
    #include <string> 

    using std::cin; 



    int tmain (int argc, _TCHAR* argv[]) 
    { 


     BaseMenu* aCurrentMenu = new MainMenu;   // Pointer to the current working menu 

     bool isQuitOptionSelected = false; 
     while (!isQuitOptionSelected)     // set to keep menus running until the quit option is selected 
     { 

      aCurrentMenu->printText();     // call and print the menu text for the currently active menu 

      int choice = 0;        // Initializing choice variable and setting it to 0 
      cin >> choice; 

      BaseMenu* aNewMenuPointer = aCurrentMenu->getNextMenu(choice, isQuitOptionSelected); // This will return a new object, of the type of the new menu we want. Also checks if quit was selected //**This is the line that the error is reported**// 

      if (aNewMenuPointer) 
      { 
       delete aCurrentMenu;     // clean up the old menu 
     aCurrentMenu = aNewMenuPointer;     // updating the 'current menu' with the new menu 
      } 
     } 

     return true;  
    } 

出於某種原因,我想不通,我收到一個

錯誤C2440:'初始化':無法從'BaseMenu'轉換爲'BaseMenu *'。這個錯誤是在35行的主要.cpp文件,這是

"BaseMenu* aNewMenuPointer = aCurrentMenu->getNextMenu(choice, isQuitOptionSelected);" 

我已經看過本網站和其他多個類似的問題。我試過的解決方案之一導致了我所有菜單類的多個鏈接錯誤。我花了3天時間纔將錯誤減少到僅剩下這一個錯誤,而我卻處於虧損狀態。

+1

'BaseMenu :: getNextMenu'被聲明爲返回'BaseMenu'的*實例*,但'aNewMenuPointer'是'BaseMenu'的一個*指針。一個值和一個指向值的指針是兩個完全不同的東西。 –

回答

0

編譯器告訴你這個問題。 getNextMenu會返回一個實際的BaseMenu對象,但您試圖將其分配給指向BaseMenu對象的指針。

相關問題