在c ++中使用静态类

时间:2012-12-09 08:03:20

标签: c++ file compilation header

我在C ++中有一些简单的假设静态类:

#ifndef __STAT_H_
#define __STAT_H_

class Stat {

 private:
  static vector<int> v;

 public:

  static void add_num(int num);
  static void clear_nums();
  static void get_count();
};

#endif

ccp文件是这样的:

#include "Stat.h"

vector<int> v;


void Stat::add_num(int num) {
  v.push_back(num);
}

void Stat::clear_nums() {
  v.clear();
}

int Stat::get_num_count() {
  return v.size();
}

现在当我在main.cpp文件中包含“Stat.h”并尝试使用一些静态方法时:

Stat::add_num(8);

编译期间的错误是

对'Stat :: add_num(int)'

的未定义引用

在这种情况下可能出现什么问题?谢谢。

编辑:抱歉地址矢量,应该是那里

3 个答案:

答案 0 :(得分:3)

听起来你没有在编译中包含stat.cpp。因此,您的链接器无法找到静态方法的实现。

答案 1 :(得分:1)

你需要在g ++命令中链接Stat.o,比如说:

g++ -c -o Stat.o Stat.cpp
g++ -o Stat main.cpp Stat.o

我想你的Stat.cpp:

vector<int> v;

应该是:

vector<int> Stat::v;

如果在Stat.cpp中定义本地v,则没有编译错误,但我想您打算使用Stat::v

答案 2 :(得分:1)

这是我对你的计划的看法,仅供参考。

Stat.h

#ifndef STAT_H
#define STAT_H

#include <vector>
using std::vector;

class Stat
{
 public:
  static void add_num(int num);
  static void clear_nums();
  static int get_count();

 private:
  static vector<int> v;
};

#endif

Stat.cpp

#include "Stat.h"

vector<int> Stat::v;

void Stat::add_num(int num) { v.push_back(num); }

void Stat::clear_nums() { v.clear(); }

int Stat::get_count() { return v.size(); }

的main.cpp

#include "Stat.h"

int main()
{
  Stat s;
  s.add_num(8);
}

生成文件

CC = g++
OBJS = Stat.o
DEBUG = -g
CFLAGS = -Wall -c $(DEBUG)
LFLAGS = -Wall $(DEBUG)

all: build clean

build: $(OBJS)
        $(CC) main.cpp $(LFLAGS) $(OBJS) -o stat

Stat.o: Stat.h
        $(CC) $(CFLAGS) Stat.cpp

clean:
        -rm -f *.o