2015-01-23 5 views
1

누군가 내가 잘못하고있는 것을 도와 줄 수 있습니까? 항상 기본 클래스 포인터가 호출됩니다! 나는 사용자 정의 클래스 객체의 Map을 만들기 위해 노력하고있다. find와 indexing을 통해 직접 시도해 보았지만 같은 결과를 얻었습니다!가상 함수, 기본 클래스 함수가 ​​여기에서 호출되는 이유는 무엇입니까?

#include "stdafx.h" 
#include <iostream> 
#include <string> 
#include <Map> 
#include <algorithm> 

class Command 
{ 
public: 
    virtual int execute(std::string *args) { std::cout << "Base called ! ERROR!\n"; return -1; } 
}; 

class ShowNames : public Command 
{ 
public: 
    int execute(std::string names) 
    { 
     std::cout << names; 
     return 0; 
    } 
}; 

class ShowNos : public Command 
{ 
public: 
    int execute(std::string Nos) 
    { 
     std::cout << Nos; 
     return 0; 
    } 
}; 

typedef std::map<std::string, Command*> CmdList; 

CmdList buildMaps() 
{ 
    CmdList c1; 
    ShowNames s1; 
    ShowNos n1; 

    c1["names"] = new ShowNames(); 
    c1["nos"] = new ShowNos(); 

    //c1.find("names") 

    return c1; 
} 

void testCommandList() 
{ 
    CmdList commands; 
    Command *c1; 
    commands = buildMaps(); 

    std::string cmd,args; 
    std::cout << "Enter your command: "; 
    std::cin >> cmd; 
    std::cout << "Enter args for the command: "; 
    std::cin >> args; 

    auto it = commands.find(cmd); 
    if (it != commands.end()) 
    { 
     it->second->execute(&args); 
    } 
    else 
    { 
     std::cout << "Command not found, try again\n"; 
    } 

} 

답변

7

파생 클래스에서 기본 함수를 재정의하지 않으면 새 함수를 선언하고 있습니다. 기능 유형을 비교 : (필요한 경우, 공변 반환 형식 제외)

int Command::execute(std::string *args) 
int ShowNames::execute(std::string names) 
int ShowNos::execute(std::string Nos) 

가 기본 수준의 기능을 무시하려면 (더 분명하게 정렬), 당신은 정확하게 서명과 일치해야합니다. 따라서 서명을 동일하게 변경하십시오. 물론 올바른 도메인은 문제 도메인에 따라 다릅니다.

이 때문에 C++ 11에서는 기본 클래스 기능을 재정의하려는 가상 함수에 넣을 수있는 예약어 override을 소개했습니다. 그런 경우가 아니면 컴파일 오류가 발생합니다. 당신이 C++ (11)에 액세스 할 수있는 경우는 다음과 같이 그것을 의미 할 때, 당신은 항상를 사용해야합니다

class ShowNames : public Command 
{ 
public: 
    int execute(std::string names) override 
    { 
     std::cout << names; 
     return 0; 
    } 
}; 

는 어떤 기본 클래스의 기능을 대체하지 않습니다이 즉시 당신에게 말할 것입니다, 당신은 것 이유를 조사하기에 훨씬 좋은 위치에 있어야합니다.

+0

정보를 알려 주셔서 감사합니다. – vinit

4

실제로는 기본 클래스 방법을 덮어 쓰지 않습니다.

virtual int execute(std::string *args) 

이것은 서명입니다. 당신은 그것에 충실해야하고 그것을 바꾸지 않아야합니다.

+0

고마워요, 그걸 고쳤습니다 .... 어떻게 내 바보 야 !! – vinit

관련 문제