求助贴,从计算机科学丛书 数据结构、算法这本书里复制的简单例子,为什么会报错无法解析的外部符号

Rivia_Geralt 2024-01-05 18:11:17
#pragma once
#ifndef Currency_H
#define Currency_H

enum signType
{
    Plus,
    Minus
};

class Currency;
class Currency
{
public:
    Currency(signType theSign = signType::Plus, unsigned long dollars = 0, unsigned int cents = 0);
    ~Currency() {};
    void SetValue(signType, unsigned long, unsigned int);
    void SetValue(double);
    signType GetSign() const { return sign; };
    unsigned long GetDollars() const { return dollars; };
    unsigned int GetCents() const { return cents; };
    Currency Add(const Currency& ) const;
    //Currency& Increment(const Currency& cur);
    void output() const;
private:
    signType sign;
    unsigned long dollars;
    unsigned int cents;
};




#endif
#include "Currency.h"
#include <iostream>

using namespace std;
void Currency::SetValue(signType sType, unsigned long udDollars, unsigned int uiCent)
{
    if (uiCent > 99)
        throw "Too many cents,WTF?";

    sign = sType;
    dollars = udDollars;
    cents = uiCent;
}

void Currency::SetValue(double money)
{
    if (money < 0)
    {
        sign = Minus;
    }
    else
    {
        sign = Plus;
    }

    dollars = (unsigned long)money;
    cents = 100 * money - 100 * dollars;
}

Currency Currency::Add(const Currency& cur) const
{
    long a1, a2, a3;
    a3 = 10;
    Currency res;
    a1 = 100 * dollars + cents;
    if (sign == Minus)
        a1 = -a1;
    a2 = 100 * cur.dollars + cur.cents;
    if (cur.sign == Minus)
        a2 = -a2;
    a3 = a1 + a2;

    if (a3 < 0) { res.sign = Minus; a3 = -a3; }
    else
    {
        res.sign = Plus;
    }
    res.dollars = a3 / 100;
    res.cents = a3 - res.dollars * 100;
    return res;
}
//
//Currency& Currency::Increment(const Currency& cur)
//{
//    // TODO: 在此处插入 return 语句
//    *this = Add(cur);
//    return *this;
//}

void Currency::output() const
{
    if (sign == Minus) std::cout << '-';
    std::cout << 'S' << dollars << '.';
    if (cents < 10) cout << '0';
    cout << cents;
}

Add函数会导致报错LNK2019,无法解析的外部符号,难道类的成员函数就不能调用自身类的成员吗?

...全文
170 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
tianyingang 2024-01-10
  • 打赏
  • 举报
回复

你需要先复习下语法

Mini_hailang_IT 2024-01-06
  • 打赏
  • 举报
回复

构造函数定义错误:
在类定义中,构造函数的定义应在类的内部进行,而不是在类外部。可以将构造函数的定义移动到类的内部来修复此问题。
析构函数定义错误:
在类定义中使用了空的析构函数定义,应该将其移除。如果不需要自定义析构逻辑,可以完全省略析构函数的定义。

Rivia_Geralt 2024-01-08
  • 举报
回复
@Mini_hailang_IT 请问您指的构造函数在类的外部是怎么说,这个构造函数我不太懂,Currency(signType theSign = signType::Plus, unsigned long dollars = 0, unsigned int cents = 0);这不算是在类的内部定义的吗
Rivia_Geralt 2024-01-05
  • 打赏
  • 举报
回复

请问各位,我把构造和析构函数注释掉了就通过了,请问这是什么原因?

21,129

社区成员

发帖
与我相关
我的任务
社区描述
从0开始学一门编程语言,最重要的是开始和坚持。社区由官方CSDN创建,邀请资深讲师、博主加入,参与学习、答题
学习开源 高校 北京·朝阳区
社区管理员
  • CSDN学习
  • ZzSmart
  • SoftwareDevOps
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

《CSDN学习社区管理规范》出炉啦~

详情请点击->阅读

规范内包含CSDN学习社区对各大社员的

“福利” 与 “社区管理细则”

请务必详情阅读哦~

试试用AI创作助手写篇文章吧