简体   繁体   English

C ++模板类更改静态成员的值

[英]C++ template class change static member's value

I have the following classes - class Matrix<T> that stands for a matrix of objects of type T , and it's super class baseMAtrix that holds a static boolean variable parallel_ common to all types of Matrix<T> . 我有以下类-类Matrix<T>代表类型T的对象的矩阵,它是超类baseMAtrix ,其中包含对所有Matrix<T>类型通用的静态布尔变量parallel_

I want to access parallel_ but it seems my code does not link - 我想访问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;
    }
};

I get the this message - 我收到此消息-

`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`

the Tester.cpp file is where I call setParallel - 我将Tester.cpp文件称为setParallel

Matrix<int>::setParallel(true);

is this the proper way to call setParallel ? 这是调用setParallel的正确方法吗?

is this the proper way to access baseMatrix::_parallel ? 这是访问baseMatrix::_parallel的正确方法吗?

If you want to stay just-header-friendly, you could change base class to template: 如果您想保持标题友好,可以将基类更改为模板:

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

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

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

This way there is no need for baseMatrix::_parallel in cpp file. 这样,在cpp文件中就不需要baseMatrix::_parallel

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM