对foo::bar static ofstream的未定义引用

Undefined reference to foo::bar static ofstream

本文关键字:未定义 ofstream 引用 static foo bar      更新时间:2023-10-16

我一直在尝试编译一个我花了三天时间构建的程序,但我不知道如何让它停止抛出错误。我一直得到编译错误"对Foo::bar的未定义引用",其中"bar"是在Foo.h文件中声明的静态ofstream。

foo。

Class Foo
{
    public:
          <insert methods>
    private:
          static ofstream& bar;
 }

Foo.cpp

#include <iostream>
#include <fstream>
#include <sstream>
#include "EventReport.h"
using namespace std;
Foo::Foo()
{
   bar.open("foobar.txt");
}

我一直在Foo.cpp中的"bar"上获得错误消息(文件中有多个)。知道为什么吗?

undefined reference to Foo::bar

这个错误意味着你告诉编译器这个对象存在…

class Foo {
      static ofstream& bar;
};

…编译器决定使用它

但是你从来没有定义过。这是未定义的。

添加到Foo.cpp:

ofstream& Foo::bar = (something);