c++ - 设置类静态

标签 c++ class templates variable-declaration

我正在尝试编写一个类(class)作为练习,并具有以下内容:

template <class Foo>
class Bar
{
protected:
    Foo _x,_y,_z;
public:
    Bar(Foo x, Foo y, Foo z) {_x=x; _y=y; _z=z;};
    Bar() {_x=0; _y=0; _z=0;};

    static const Bar<Foo> X;
};

我想将 X 初始化为 (0,1,0) 但不知道该怎么做。我想声明 X =(0,1,0) 就像在程序开始时声明 #define pi = 3.142 一样。我应该怎么做?

最佳答案

您所做的一切都很好,但您可能会遇到链接器错误,因为您没有为 X 提供任何存储空间| .你需要这样做:

template <class Foo>
class Bar
{
protected:
    Foo _x,_y,_z;
public:
    Bar(Foo x, Foo y, Foo z) {_x=x; _y=y; _z=z;};
    Bar() {_x=0; _y=0; _z=0;};

    static const Bar<Foo> X;
};

template <typename Foo>
const Bar<Foo> Bar<Foo>::X(0, 1, 0);

与非模板静态变量不同,这可以放在标题中——与其他模板一样,Bar<Foo>::X 的重复定义将在链接时合并。

关于c++ - 设置类静态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20558065/

相关文章:

c++ - 什么可能导致确定性过程产生浮点错误

c++ - 如何在运行时更改 srand()

templates - 转到 HTML 模板 : Can I stop the templates package inserting quotes around strings in scripts?

c++ - 提高OpenGL渲染性能: rendering multiple times from different POVs

python - 以dict形式访问类属性 python django

javascript - 在 ES6 类中添加上下文/私有(private)变量(不引用 this。)

java - 奇怪的运行时错误声明类 Java 的实例

c++ - 使用模板定义 bitset 的大小

java - 在 Java 中创建虚拟模板方法

c++ - 请协助 : "if" statement in C++