未明确引用`saving :: rate'

时间:2017-03-22 20:16:04

标签: c++

我正在编写这段代码,但是当我在arch linux中用g ++编译这段代码时,我发现了这个错误

  /tmp/ccG7axw1.o: In function `saving::calculate()':
  saving.cpp:(.text+0x3a): undefined reference to `saving::rate'
  /tmp/ccG7axw1.o: In function `saving::modify()':
  saving.cpp:(.text+0x93): undefined reference to `saving::rate'
  collect2: error: ld returned 1 exit status

saving.h

class saving{
private :
    double savebal;
public :
    saving(double newSavebal); 
    double calculate();
    void modify();
    static double rate;
};

saving.cpp

#include<iostream>
#include"saving.h"
using namespace std;
saving :: saving(double newSavebal){
   savebal = newSavebal;
}
double saving :: calculate(){
    savebal += (savebal * (rate / 100))/12;
}

void saving :: modify(){
    cout<<"Please enter the new rate"<<endl;
    cin>>rate;
}

mainSaving.cpp

#include<iostream>
#include"saving.h"
using namespace std;
void menu(saving );
int main(){
      saving s1(500);
      menu(s1);
}

  void menu(saving s){
    int m;
    cout<<"1) calculate month interest\n";
    cout<<"2) change rate of interest\n";
    cin>>m;
    switch(m){
        case 1 :
         s.calculate();
         break;
        case 2 :
         s.modify();
         break;

    }
}

2 个答案:

答案 0 :(得分:0)

Saving.h中,您声明了静态变量:

static double rate;

但是你仍然需要定义它(换句话说,实例化它)。为此,您应将其添加到Saving.cpp

 double saving::rate = 0;

如果不这样,链接器就找不到实际的变量,因此对它的任何引用都会导致链接器错误。

答案 1 :(得分:0)

因为save是一个静态成员,所以你必须事先初始化它。

saving.cpp文件中,在包含所有标题后添加此行:

double saving::rate = 0

Your code should then like this:
#include<iostream>
#include"saving.h"
using namespace std;

double saving::rate = 0; //With this line here

saving :: saving(double newSavebal){
   savebal = newSavebal;
}