【问题标题】:Unresolved external symbol error in c++C ++中未解决的外部符号错误
【发布时间】:2011-12-22 17:44:38
【问题描述】:

我正在尝试解决一个涉及命名空间、静态数据成员和函数的简单硬件问题。我收到一个未解决的外部符号错误

Error   1   error LNK2001: unresolved external symbol "private: static double JWong::SavingsAccount::annualInterestRate" (?annualInterestRate@SavingsAccount@JWong@@0NA)    SavingsAccount.obj  SavingsAccount

而且我不明白为什么会出现此错误。与导致此错误的常规数据成员相比,也许我对静态变量一无所知。这是我的代码:

SavingsAccount.h 文件

#ifndef JWONG_SAVINGSACCOUNT_H
#define JWONG_SAVINGSACCOUNT_H

namespace JWong
{
    class SavingsAccount
    {
    public: 
        // default constructor
        SavingsAccount();
        // constructor
        SavingsAccount(double savingsBalance);

        double getSavingsBalance();
        void setSavingsBalance(double savingsBalance);
        double calculateMonthlyInterest();

        // static functions
        static void modifyInterestRate(double newInterestRate);
        static double getAnnualInterestRest();
    private:
        double savingsBalance;

        // static members
        static double annualInterestRate; 
    };
}

#endif

SavingsAccount.cpp 文件

#include <iostream>
#include "SavingsAccount.h"

// default constructor, set savingsBalance to 0
JWong::SavingsAccount::SavingsAccount() : savingsBalance(0)
{}

// constructor
JWong::SavingsAccount::SavingsAccount(double savingsBalance) : savingsBalance(savingsBalance)
{}

double JWong::SavingsAccount::getSavingsBalance()
{
    return savingsBalance;
}

void JWong::SavingsAccount::setSavingsBalance(double savingsBalance)
{
    this->savingsBalance = savingsBalance;
}

// returns monthly interest and sets savingsBalance to new amount
double JWong::SavingsAccount::calculateMonthlyInterest()
{
    double monthlyInterest = savingsBalance * SavingsAccount::annualInterestRate / 12; 
    setSavingsBalance(savingsBalance + monthlyInterest);
    return monthlyInterest; 
}

void JWong::SavingsAccount::modifyInterestRate(double newInterestRate)
{
    SavingsAccount::annualInterestRate = newInterestRate;
}

double JWong::SavingsAccount::getAnnualInterestRest()
{
    return SavingsAccount::annualInterestRate;
}

【问题讨论】:

标签: c++


【解决方案1】:

我假设您实际上是在编译 .cpp 文件(因为其他函数链接)。

该错误可能是由于未定义 annualInterestRate 静态变量。

你已经声明了它(在类头文件中),但它没有被定义。在你的 cpp 文件中添加:

// static member definition
double JWang::SavingsAccount::annualInterestRate = ...;

查看一篇文章,重点介绍静态成员declaration and definition 之间的区别。

C++ 标准的第 9.4.2 节说“静态数据成员的定义应出现在包含该成员的类定义的命名空间范围内。”

【讨论】:

    【解决方案2】:

    你需要在你的 cpp 文件中有一行

    double JWong::SavingsAccount::annualInterestRate = 0.7;  // or whatever you like 
    

    【讨论】:

    • 我认为静态成员被初始化为 0?还是会在以后发生?
    • 无论哪种方式,您的程序在定义之前都不是很好的格式。
    猜你喜欢
    • 2021-10-30
    • 2011-09-03
    • 2010-11-20
    • 1970-01-01
    • 1970-01-01
    • 2012-02-28
    • 2013-07-20
    • 2015-06-15
    • 2023-03-05
    相关资源
    最近更新 更多