本文介绍了有麻烦的联系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我有一个具有静态成员的模板类,因此在.cpp文件中我用定义了模板化定义。现在,在另一个包含模板类头文件的 ..cpp文件中,我从模板类派生了一个新类,并将该类作为模板传递 参数(CRTP)。现在,当我实例化这个新类时,它会抱怨它 无法找到静态。模板定义是不是定义了它们? 代码编译得很好但会导致链接器错误。 这是一个简单的例子,说明了什么导致了麻烦.... 标题.... #ifndef CTYPE #define CTYPE #include< cstddef> 命名空间ns { 模板< typename CT> class OC { public: static std :: size_t count() { 返回OC< CT>: :c_; } 受保护: OC() { ++ OC< CT> :: c_; } OC(const OC< CT>&) { ++ OC< CT> :: c_; } ~OC() { --OC< CT> :: c_; } 私人: static std :: size_t c_; } ; } #endif ..cpp .... #include" ; templates.h" 命名空间ns { //强制性静态定义 模板< typename CT> std :: size_t OC< CT> :: c_ = 0; } main.cpp #include" templates.h" #include< iostream> 使用命名空间std; class C:private ns :: OC< C> { public: 使用ns :: OC< C> :: count; }; int main() { C array [3]; cout<< C :: count()<< endl; 返回0; } 如何制作我的代码可链接以及可编译? I have a template class that has static members, so in the .cpp file Ihave defined them with templated definitions. Now when in a different..cpp file that includes the header file for the template class I derivea new class from the template class and pass that class as its templateparameter (CRTP). Now when I instantiate this new class it complains itcannot find the statics. Doesnt the template definition define them?The code compiles fine but causes linker errors.heres a boiled down example of whats causing the trouble.... header....#ifndef CTYPE#define CTYPE#include <cstddef>namespace ns{template <typename CT>class OC{public:static std::size_t count(){return OC<CT>::c_;}protected:OC(){++OC<CT >::c_;}OC( const OC< CT >& ){++OC< CT >::c_;}~OC(){--OC< CT >::c_;}private:static std::size_t c_;};}#endif ..cpp ....#include "templates.h" namespace ns{// mandatory static definitiontemplate < typename CT >std::size_t OC< CT >::c_ = 0;} main.cpp#include "templates.h"#include <iostream>using namespace std; class C : private ns::OC<C>{public:using ns::OC<C>::count;}; int main(){C array[3];cout << C::count()<<endl;return 0;} How do I make my code linkable as well as compileable? 推荐答案 这是错的,所有模板代码都必须放在头文件中,包括 静态会员。 john This is wrong, all template code must go in header files, that includesstatic members. john 不,模板是不同的。我知道这看起来很奇怪,但它是正确的 要做的事情。所有模板代码都在头文件中,链接器将知道消除重复定义。 尝试阅读常见问题 http://www.parashift.com/c++-faq-lite /templates.html 问题35.7起。 john No, templates are different. I know it seems strange but it''s the rightthing to do. All template code goes in header files, the linker willknow to eliminate duplicate definitions. Try reading the FAQ http://www.parashift.com/c++-faq-lite/templates.html question 35.7 onwards. john 这篇关于有麻烦的联系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 10-15 03:42