2016-09-24 44 views
0

我有以下类 - Matrix<T> 类代表T类型的对象的矩阵,它的超类baseMAtrix保存一个静态布尔变量parallel_于所有类型的Matrix<T>C++模板类变化的静态成员的值

我要访问parallel_但似乎我的代码不链接 -

class baseMatrix { 
protected: 
    static bool parallel_; 
}; 

template<class T> 
class Matrix : baseMatrix{ 

public: 
    static void setParallel (bool parallel){ 
     if(parallel != baseMAtrix::parallel_){ 
      cout << "message" << endl; 
     } 
     baseMAtrix::parallel_ = parallel; 
    } 
}; 

我得到这个消息 -

`CMakeFiles/ex3.dir/Tester.cpp.o:Tester.cpp:(.rdata$.refptr._ZN10baseMatrix9_parallelE[.refptr._ZN10baseMatrix9_parallelE]+0x0): undefined reference to `baseMatrix::_parallel' 
collect2: error: ld returned 1 exit status` 

Tester.cpp文件是我叫setParallel -

Matrix<int>::setParallel(true);

这是拨打setParallel的正确方法吗?

这是访问baseMatrix::_parallel的正确方法吗?

+0

技术上你只需要定义变量。 'bool baseMatrix :: _ parallel;'在某个地方的全局范围内。顺便说一句,你可以通过避免全局变量(这是)避免了额外的工作,并且通过使用单个约定来对类型名称进行大写。 –

+0

@ Cheersandhth.-Alf你是什么意思?为什么MAtrix无法访问其超类的成员? 我不能定义一个全局变量,因为我不是要使用类 – proton

+0

此外,而不是带有前导下划线的约定,考虑尾部下划线(例如用于Boost)。领先的下划线是一种用于不同事物的约定,即用于由实现定义的名称。因此,在全局命名空间中保留了前导下划线。 –

回答

0

如果你想留下来只是头型,你可以基类更改为模板:

template<class T> 
class baseMatrix 
{ 
protected: 
    static bool _parallel; 
}; 

template<class T> 
bool baseMatrix<T>::_parallel; 

template<class T> 
class Matrix : baseMatrix<void> 
... 

这种方式存在cpp文件不需要baseMatrix::_parallel

+0

point baseMAtrix是为了确保我可以将“parallel_”的值更改为“Matrix ”的所有时刻,而不管“T”如何。 – proton

+0

@proton:从技术上讲,如果你继承了单一的专长,比如'baseMatrix ''。我冒昧编辑答案来做到这一点。对于模板类有一个特殊的豁免,即使标题在多个翻译单元中使用,也会生成此有效的代码(“_parallel”定义中没有链接器冲突)。 –

+0

@ Cheersandhth.-Alf感谢编辑,解决了它:) – xinaiz