未定义参考

ihm*_*ihm 3 c++ g++

我的程序很简单.一类银行账户.每个帐户都有余额和权力.每个账户的利率相同.我在编译时遇到错误.怎么了?提前致谢.

  2 #include <iostream>
  3 #include <string>
  4 using namespace std;
  5 class bank
  6 {
  7 private:
  8         double balance;
  9         string owner;
 10         static double InterestRate;
 11 public:
 12         static void AccountInfo(const bank& ac)
 13         {
 14                 cout << "name: " << ac.owner << endl << "balance: " << ac.balance;
 15         }
 16         static void SetAccount(bank& ac)
 17         {
 18                 cout << "enter a name: " << flush;
 19                 cin >> ac.owner;
 20                 cout << "enter a balance: " << flush;
 21                 cin >> ac.balance;
 22         }
 23         static void SetRate(const double& n)
 24         {
 25                 InterestRate = n;
 26         }
 27         static void Balance(bank& ac)
 28         {
 29                 ac.balance += ac.balance * InterestRate;
 30         }
 31 };
 32 int main ()
 33 {
 34         bank NewAccount;
 35         bank::SetAccount(NewAccount);
 36         bank::SetRate(0.15);
 37         bank::Balance(NewAccount);
 38         bank::AccountInfo(NewAccount);
 39 return 0;
 40 }
Run Code Online (Sandbox Code Playgroud)

输出是:

  /tmp/ccUh8Sd9.o: In function `bank::SetRate(double const&)':
    e1237.cpp:(.text._ZN4bank7SetRateERKd[bank::SetRate(double const&)]+0x12): undefined reference to `bank::InterestRate'
    /tmp/ccUh8Sd9.o: In function `bank::Balance(bank&)':
    e1237.cpp:(.text._ZN4bank7BalanceERS_[bank::Balance(bank&)]+0x1c): undefined reference to `bank::InterestRate'
    collect2: ld returned 1 exit status
Run Code Online (Sandbox Code Playgroud)

Alo*_*ave 8

您刚刚InterestRate在类定义中声明了静态成员,但是,
您还需要在一个cpp文件中定义静态成员:

double bank::InterestRate = 0.0;
Run Code Online (Sandbox Code Playgroud)

如果没有这个,链接器将无法找到其定义并给出链接错误.