未定义的静态成员引用

时间:2018-02-27 01:53:55

标签: c++ ubuntu static-methods static-members geany

每次尝试编译以下代码时,我都会继续获取对静态成员的未定义引用:

main.cpp中:

#include <iostream>
#include <iomanip>
#include "Obj1.h"
using namespace std;

int main(){
    double value;
    cout << "Enter shared val: ";
    cin >> value;
    obj1::initialize(value); //static member function called
    obj1 object;
    cout << "\nValue: " << object.getSharedVal();//prints static member var
}

Obj1.h:

#ifndef OBJ1_H
#define OBJ1_H

class obj1{
    private:
        static double sharedVal; 
        double val;
    public:  
        obj1(){
            val = 0;
        }
        void add(double d){
            val += d;
            sharedVal += d;
        }
        double getVal() const{
            return val;
        }
        double getSharedVal() const{
            return sharedVal;
        }
        static void initialize(double);
};

#endif

Obj1.cpp:

#include "Obj1.h"

double obj1::sharedVal = 0; //define static members outside class.

void obj1::initialize(double d){
    sharedVal += d;
}

当我尝试编译main.cpp(使用g++ main.cpp)时,出现以下错误:

/tmp/cc51LhbE.o: In function `main':
objectTester.cpp:(.text+0x45): undefined reference to `obj1::initialize(double)'
/tmp/cc51LhbE.o: In function `obj1::getSharedVal() const':
objectTester.cpp:(.text._ZNK4obj112getSharedValEv[_ZNK4obj112getSharedValEv]+0xc): undefined reference to `obj1::sharedVal'
collect2: error: ld returned 1 exit status

为什么会出现此错误?

此外:我在Ubuntu 16.04中使用Geany Text Editor,这是一个我完全不熟悉的文本编辑器。我也注意到Geany的.h文件,私有,公共和类等关键字不像.cpp文件那样使用粗体字。这是为什么?

0 个答案:

没有答案