This question already has answers here:
What is an undefined reference/unresolved external symbol error and how do I fix it?
                                
                                    (32个答案)
                                
                        
                        
                            static variable link error
                                
                                    (2个答案)
                                
                        
                                2年前关闭。
            
                    
我正在编写此代码,但是当我在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



保存.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;

    }
}

最佳答案

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

static double rate;


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

 double saving::rate = 0;


否则,链接器将找不到实际的变量,因此对它的任何引用都将导致链接器错误。

关于c++ - 未定义对`saving::rate'的引用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42961807/

10-14 15:19
查看更多