[英]Call static member from inherited class instance
I have two classes, Y
and X
, and Y
holds some static members -- which I'm trying to access via an X
instance: 我有两个类,
Y
和X
, 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;
}
Even though it compiles, it does not link correctly: 即使编译,也无法正确链接:
$ 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
Context (if it matters): 上下文 (如果重要):
I'm trying to write a memory manager -- class Y
-- that statically holds a pool of memory, so that all the instances of a class X
use memory blocks provided by Y
. 我正在尝试编写一个内存管理器-
class Y
静态地持有一个内存池,以便class X
所有实例都使用Y
提供的内存块。
I'm not sure if this is the best approach on what I'm trying to do, but was the somewhat most elegant way I thought of so far. 我不确定这是否是我尝试做的最好的方法,但这是到目前为止我想到的最优雅的方法。 Any ideas are very much welcome.
任何想法都非常欢迎。
Static data members have to be defined as well as declared. 静态数据成员必须定义和声明。 If this was an ordinary class you'd do it like this:
如果这是一个普通的类,您可以这样做:
// 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;
Since the function value
is static it is common to all instances of class Y
. 由于函数
value
是静态的,因此对于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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.