我想static const char在班上有一个数组.海湾合作委员会抱怨并告诉我应该使用constexpr,虽然现在它告诉我这是一个未定义的参考.如果我使数组成为非成员,那么它将编译.到底是怎么回事?
// .hpp
struct foo {
void bar();
static constexpr char baz[] = "quz";
};
// .cpp
void foo::bar() {
std::string str(baz); // undefined reference to baz
}
Run Code Online (Sandbox Code Playgroud) 我的理解是C++允许在类中定义静态const成员,只要它是整数类型即可.
那么,为什么以下代码会给我一个链接器错误?
#include <algorithm>
#include <iostream>
class test
{
public:
static const int N = 10;
};
int main()
{
std::cout << test::N << "\n";
std::min(9, test::N);
}
Run Code Online (Sandbox Code Playgroud)
我得到的错误是:
test.cpp:(.text+0x130): undefined reference to `test::N'
collect2: ld returned 1 exit status
Run Code Online (Sandbox Code Playgroud)
有趣的是,如果我注释掉对std :: min的调用,代码编译和链接就好了(即使test :: N也在前一行引用).
知道发生了什么事吗?
我的编译器是Linux上的gcc 4.4.
使用以下代码时,我对链接器错误感到困惑:
// static_const.cpp -- complete code
#include <vector>
struct Elem {
static const int value = 0;
};
int main(int argc, char *argv[]) {
std::vector<Elem> v(1);
std::vector<Elem>::iterator it;
it = v.begin();
return it->value;
}
Run Code Online (Sandbox Code Playgroud)
但是,这在链接时失败 - 不知何故,它需要有一个静态const"值"的符号.
$ g++ static_const.cpp
/tmp/ccZTyfe7.o: In function `main':
static_const.cpp:(.text+0x8e): undefined reference to `Elem::value'
collect2: ld returned 1 exit status
Run Code Online (Sandbox Code Playgroud)
顺便说一句,这与-O1或更好的编译很好; 但对于更复杂的情况,它仍然失败.我使用的是gcc版本4.4.4 20100726(Red Hat 4.4.4-13).
任何想法我的代码可能有什么问题?
#include<iostream>
using namespace std;
class A
{
private:
const int a=9;
public:
void display()
{
cout<<a;
}
};
int main()
{
A a;
a.display();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
为什么不允许初始化const int a = 9.但是,如果我写了常量静态int a = 9编译器没有显示任何错误.写const static int a = 9是什么意思?我什么时候写这样的?
〜
c++ ×4
static ×2
c++11 ×1
const ×1
constexpr ×1
declaration ×1
definition ×1
gcc ×1
stdvector ×1