21,129
社区成员
发帖
与我相关
我的任务
分享
#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,无法解析的外部符号,难道类的成员函数就不能调用自身类的成员吗?
你需要先复习下语法
构造函数定义错误:
在类定义中,构造函数的定义应在类的内部进行,而不是在类外部。可以将构造函数的定义移动到类的内部来修复此问题。
析构函数定义错误:
在类定义中使用了空的析构函数定义,应该将其移除。如果不需要自定义析构逻辑,可以完全省略析构函数的定义。
请问各位,我把构造和析构函数注释掉了就通过了,请问这是什么原因?