2016-04-22 61 views
2

下面是完整的代码到我的项目(没有代码已被省略):为什么编译器会说“Static_cast与哪个不相关”?

#include <iostream> 
#include <string> 
#include <vector> 
#include <unordered_map> 

typedef enum{ 
    MAJOR_BUTTON_IGNORED_FIRST = 0, 
    MAJOR_BUTTON_BLOCKS, 
    MAJOR_BUTTON_IGNORED_LAST, 
}MAJOR_BUTTON_TYPE; 


typedef enum{ 
    BLOCK_IGNORED_FIRST = 0, 
    BLOCK_ORDINARY_SMASHABLE, 
    BLOCK_IGNORED_LAST, 
}THING_TYPE; 

class Datar{ 
private: 
public: 

    MAJOR_BUTTON_TYPE majorType; 
    std::string majorButtonString; 
    std::vector<THING_TYPE>thingTypes; 
    std::unordered_map<THING_TYPE, std::string>thing2String; 

    Datar(){ 

    } 

    virtual ~Datar(){}; 
    virtual void initDatar(){}; 
}; 

class DatarBlock : public Datar{ 
private: 
public: 

    virtual void initDatar(){ 
     majorType = MAJOR_BUTTON_BLOCKS; 
     majorButtonString = "MajorButtonNames::blocks"; 

    } 

}; 

int main(int argc, const char * argv[]) { 
    // insert code here... 
    std::cout << "Hello, World!\n"; 
    DatarBlock* db = new DatarBlock(); 
    Datar* blah = static_cast<Datar*>(db); //Compiler error here **** 
    return 0; 
} 

在标线,还有它说一个编译器错误:

的main.cpp:62: 19:从的static_cast“DatarBlock *”到“达塔尔*”,这 没有继承关系,是不允许

为什么编译器报告为错误?

编辑:我使用的Xcode 7.2(LLVM 7.0),C++标准库= libc的++(LLVM标准库用C++ 11支撑),C++语言方言= GNU ++ 11

+2

[无法重现](http://rextester.com/TPGX82687)。你使用什么编译器? – songyuanyao

+0

@songyuanyao我使用Xcode 7.2(LLVM 7.0),C++标准库= libC++(支持C++ 11的LLVM标准库),C++语言Dialect = GNU ++ 11。 –

+1

你为什么发布你刚才删除的同一个问题? http://stackoverflow.com/questions/36785524/why-does-the-compiler-think-that-these-two-classes-are-not-related-by-inheritanc/ –

回答

4

该代码是无效C++ 11(没有DR 2148),其中std::hash未专门针对枚举类型(有关概述,请参阅http://en.cppreference.com/w/cpp/utility/hash)。但是它通过libstdC++ 4.6被接受(我没有libc++的版本号)。

C++ 14的增益所需的专门化,但它们不实现为的libstdC++ 5.他们在的libstdC++ 6实现的,请参阅GCC bug 60970DR 2148,并且有意在C++ 11模式可用。无论我使用的是什么版本的libC++ 仅支持C++ 14模式。

这就是为什么你需要看所有错误,为了,因为先前的错误可能导致以后的错误完全没有意义的例子。

+1

使用'--std = C++ 11'编译的证明失败,但使用'--std = C++ 14'编译成功。 –

+0

@ Jean-BaptisteYunès对您的实施产生了极大的信任。我更喜欢标准的证据,或者至少是一个小心参考标准的网站。 – o11c

+0

从与GCC维护者的讨论来看,DR的存在意味着它在* -std = C++ 11'模式下应该是可以接受的。 – o11c