C++ static variable initialization

来源:互联网 发布:web聊天室源码 编辑:程序博客网 时间:2024/05/17 04:01

Because static member variables are not part of the individual objects, you must explicitly define the static member.

If you fail to initialize the static variable,Undefined Reference to staticVal will occur!

Example.h

#ifndef EXAMPLE_H_#define EXAMPLE_H_class Example {public:    Example();    virtual ~Example();protected:    static int staticVal;};#endif /* EXAMPLE_H_ */
Example.cpp

#include "Example.h"#include <iostream>int Example::staticVal = 3;Example::Example() {   std::cout << staticVal << std::endl;}
Main.cpp

#include "Example.h"int main(int argc, char **argv) {    Example* ep = new Example();}