C++技巧(warningC4786錯(cuò)誤解決方法)

字號(hào):

在使用std::vector的過程中,考試大提示編譯器報(bào)了如下的warning:
    c:\program files\vc98\include\vector(61) : warning C4786: '??0?$vector@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@V?$allocator@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@2@@std@@QAE@PBV?$basic_string@DU?$char_t
    raits@D@std@@V?$allocator@D@2@@1@0ABV?$allocator@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@1@@Z : identifier was truncated to '255' characters in the browser information
    d:\rtd\ruleloader\treenode.h(15) : see reference to class template instantiation 'std::vector,class std::allocator >,class std::allocator  d::char_traits,class std::allocator > > >' being compiled
    此warning產(chǎn)生的原因是因?yàn)闃?biāo)識(shí)符過長(zhǎng),超過了限定255個(gè)字。例如:
    #define a_really_long_class_name a_really_really_really_really_really_really_really_ \
    really_really_really_really_really_really_really_really_really_really_really_really_ \
    really_really_really_really_really_really_really_really_really_really_really_really_really_really_really
    class a_really_long_class_name
    {
    public:
    a_really_long_class_name() {};
    int m_data;
    };
    void main()
    {
    a_really_long_class_name test_obj;
    test_obj.m_data = 12;
    }
    類名超過了255個(gè)字,使用時(shí)就會(huì)報(bào)4786的waring。在使用STL(C++標(biāo)準(zhǔn)模板庫(kù))的時(shí)候經(jīng)常引發(fā)類似的錯(cuò)誤,尤其是vector,map這類模板類,模板中套模板,一不小心就超長(zhǎng)了。例如:
    template
    class VeryLongClassNameA{};
    template
    class VeryLongClassNameB{};
    template
    class VeryLongClassNameC{};
    template
    class VeryLongClassNameD{};
    class SomeRandomClass{};
    typedef VeryLongClassNameD ClassD ;
    typedef VeryLongClassNameC ClassC;
    typedef VeryLongClassNameB ClassB;
    typedef VeryLongClassNameA ClassA;
    void SomeRandomFunction(ClassA aobj){}
    void main()
    {
    ClassA AObj ;
    SomeRandomFunction(AObj) ;
    }
    解決方法有兩種,一種是直接定義別名:
    #ifdef _DEBUG
    #define VeryLongClassNameA A
    #define VeryLongClassNameB B
    #endif
    另一種是屏蔽4786warning:
    #pragma warning(disable : 4786)
    注意屏蔽語(yǔ)句必須放在報(bào)錯(cuò)的模板類的引用聲明(如#include )之前,否則還是不起作用。