0

我有两个类,YX,并Y拥有一些静态成员——我试图通过一个X实例访问它们:

template <class T>
class Y {
public:
    Y() {
        i = 0;
        v = std::vector<int>(10, 10);
    }
    static int value() {
        return v[i];
    }
private:
    static int i;
    static std::vector<int> v;
};

class X : public Y<X> {
public:
    X() {
    }
};

int main() {
    X *x(new X());
    std::cout << x->value() << std::endl;
}

即使它编译,它也没有正确链接:

$ g++ t.cpp
/tmp/ccB4ijzw.o: In function `Y<X>::Y()':
t.cpp:(.text._ZN1YI1XEC2Ev[Y<X>::Y()]+0x11): undefined reference to `Y<X>::i'
t.cpp:(.text._ZN1YI1XEC2Ev[Y<X>::Y()]+0x4a): undefined reference to `Y<X>::v'
/tmp/ccB4ijzw.o: In function `Y<X>::value()':
t.cpp:(.text._ZN1YI1XE5valueEv[Y<X>::value()]+0x6): undefined reference to `Y<X>::i'
t.cpp:(.text._ZN1YI1XE5valueEv[Y<X>::value()]+0x10): undefined reference to `Y<X>::v'
collect2: ld returned 1 exit status                                             

上下文(如果重要):

我正在尝试编写一个内存管理器——class Y它静态地保存一个内存池,以便所有实例都class X使用由Y.

我不确定这是否是我想要做的最好的方法,但这是我迄今为止想到的最优雅的方法。非常欢迎任何想法。

4

2 回答 2

3

必须定义和声明静态数据成员。如果这是一个普通的课程,你会这样做:

// header:
class C {
    static int i;
};

// source:
int C::i = 3;

With a class template you don't ordinarily put the code in a source file, so you'd do this:

// header:
template <class T>
class C {
    static int i;
};

template <class T>
int C<T>::i = 3;
于 2013-03-30T20:05:43.797 回答
1

Since the function value is static it is common to all instances of class Y. The way to call a static member function is like

std::cout << Y<X>::value() << std::endl;

NOT (this is not illegal but it is just not a good practice. Why make the function static i you are going to do this anyway?.)

std::cout << x->value() << std::endl;

In addition you have to define all the static members. Something like

template <class T>
int Y<T>::i = 0;

template <class T>
std::vector<int> Y<T>::v(0);
于 2013-03-30T20:07:24.600 回答