我正在编译以下简单程序g++-4.6.1 --std=c++0x:
#include <algorithm>
struct S
{
static constexpr int X = 10;
};
int main()
{
return std::min(S::X, 0);
};
Run Code Online (Sandbox Code Playgroud)
我收到以下链接器错误:
/tmp/ccBj7UBt.o: In function `main':
scratch.cpp:(.text+0x17): undefined reference to `S::X'
collect2: ld returned 1 exit status
Run Code Online (Sandbox Code Playgroud)
我意识到内联定义的静态成员没有定义符号,但我在(可能是有缺陷的)印象中使用constexpr告诉编译器始终将符号视为表达式; 所以,编译器会知道传递对符号的引用是不合法的S::X(出于同样的原因,你不能引用文字10).
但是如果S被声明为命名空间,即"命名空间S"而不是"struct S",那么一切都很好.
这是一个g++错误还是我仍然需要使用技巧来解决这个烦恼?
这是使用静态const变量的正确方法吗?在我的顶级课程(形状)
#ifndef SHAPE_H
#define SHAPE_H
class Shape
{
public:
static const double pi;
private:
double originX;
double originY;
};
const double Shape::pi = 3.14159265;
#endif
Run Code Online (Sandbox Code Playgroud)
然后在一个扩展Shape的类中,我使用Shape :: pi.我收到链接器错误.我将const double Shape :: pi = 3.14 ...移动到Shape.cpp文件,然后我的程序编译.为什么会这样?谢谢.
东西.h
1 class Something
2 {
3 private:
4 static int s_nIDGenerator;
5 int m_nID;
6 static const double fudgeFactor; // declaration - initializing here will be warning
7 public:
8 Something() { m_nID = s_nIDGenerator++; }
9
10 int GetID() const { return m_nID; }
11 };
Run Code Online (Sandbox Code Playgroud)
文件
1 #include <iostream>
2 #include "Something.h"
3
4 // This works!
5 //const double Something::fudgeFactor = 1.57;
6
7 int main()
8 {
9 Something cFirst;
10 Something cSecond;
11 Something …Run Code Online (Sandbox Code Playgroud)