在C++中初始化私有静态数据成员的最佳方法是什么?我在头文件中尝试了这个,但它给了我奇怪的链接器错误:
class foo
{
private:
static int i;
};
int foo::i = 0;
Run Code Online (Sandbox Code Playgroud)
我猜这是因为我无法从课外初始化私人成员.那么最好的方法是什么?
谁能解释为什么以下代码无法编译?至少在g ++ 4.2.4上.
更有趣的是,为什么它会在我将MEMBER转换为int时进行编译?
#include <vector>
class Foo {
public:
static const int MEMBER = 1;
};
int main(){
vector<int> v;
v.push_back( Foo::MEMBER ); // undefined reference to `Foo::MEMBER'
v.push_back( (int) Foo::MEMBER ); // OK
return 0;
}
Run Code Online (Sandbox Code Playgroud) 如何static const
在 gdb 中打印类成员的值?
说我有:
#include <iostream>
struct foo {
static const int bar = 5;
};
int main() {
std::cout << foo::bar;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
如何检查foo::bar
gdb 中的内容?
我试过:
(gdb) p foo::bar
No symbol "foo" in current context.
(gdb) p 'foo::bar'
No symbol "foo::bar" in current context.
Run Code Online (Sandbox Code Playgroud) 我有这个代码
/////////////////////////////////////Gnome.cpp文件
#include "Living.h"
class Gnome:public Living{
private:
public:
Gnome();
void drawObjects();
};
Gnome::Gnome()
{
spriteImg = new Sprite("graphics/gnome.bmp"); //<-------------this is where it says there is the error
loaded = true;
}
Run Code Online (Sandbox Code Playgroud)
///////////////////////////////////Living.h file
#include <iostream>
#include "Sprite.h"
using namespace std;
class Sprite;
class Living{
protected:
int x,y;
static Sprite *spriteImg; //= NULL;
bool loaded;
void reset();
public:
Living();
~Living();
int getX();
void setX(int _x);
int getY();
void setY(int _y);
void virtual drawObjects() =0;
};
Run Code Online (Sandbox Code Playgroud)
// living.cpp
#include "Living.h"
Living::Living() …
Run Code Online (Sandbox Code Playgroud) static_member
以下代码中无法识别静态类成员。
但是,它适用于旧版本的编译器。我使用的编译器是基于clang
.
class my_class {
public:
static int static_member;
};
int main() {
my_class::static_member = 0;
}
Run Code Online (Sandbox Code Playgroud)
要重现该错误,请将以上文件另存为c1.cpp
并运行:
VER_TAG=latest # or VER_TAG=3.1.8
docker run --rm -v $(pwd):/src emscripten/emsdk::$VER_TAG emcc /src/c1.cpp
Run Code Online (Sandbox Code Playgroud)
导致错误:
wasm-ld:错误:/tmp/emscripten_temp_o3wmmq8k/c1_0.o:未定义符号:my_class::static_member
但是,如果我使用
VER_TAG=2.0.22
(编译器的早期版本),它工作得很好。
我的代码有什么问题吗?还是与编译器实现有关?
我需要更改static const int
成员的值。我知道这有点奇怪,但是我需要它来克服我使用的框架所赋予的限制!
我已经尝试过,但是不起作用,它会显示一个错误,提示“未定义对MyClass :: staticConstMember的引用”:
class MyClass
{
static const int staticConstMember = 10;
};
int main()
{
int* toChageValue = const_cast<int*>(&MyClass::staticConstMember);
toChangeValue = 5;
std::cout<<MyClass::staticConstMember<<std::endl; // here I need to print 5
Return 0;
};
Run Code Online (Sandbox Code Playgroud)