这是我的头文件:
#ifndef EXPENSE_H
#define EXPENSE_H
// includes
#include <string>
#define string std::string
#define ostream std::ostream
#define istream std::istream
namespace ExpenseManager{
class Expense{
private:
class Inner{
int sum;
string date;
};
Inner *i;
public:
Expense(int sum);
~Expense();
// Setters
void setSum(int sum);
void setDate();
// Getters
int getSum();
string getDate();
string toString() const;
friend class Inner;
};
}
#undef string
#undef istream
#undef ostream
#endif
这是我的实现文件:
// for switching assertions off
#define NDEBUG
// for debuging output
#define DEBUG
#define DEBUG_PREFIX "--> "
// header includes
#include "Expense.h"
#include "Time.hpp"
// includes
#include <cstdlib>
#include <iostream>
#include <sstream>
// error checking includes
#include <cassert>
#include <exception>
#include <stdexcept>
namespace ExpenseManager{
using namespace std;
class Expense::Inner{
friend class Expese;
};
Expense::Expense(int sum){
#ifdef DEBUG
clog << DEBUG_PREFIX "Constructor (1 arg) called!" << endl;
#endif
setSum(sum);
assert(sum >= 0); // assure that setter "setSum" works
i = new Expense::Inner();
}
Expense::~Expense(){
#ifdef DEBUG
clog << DEBUG_PREFIX "Destructor called!" << endl;
#endif
delete i;
}
// Setters
void Expense::setSum(int sum = 0){
#ifdef DEBUG
clog << DEBUG_PREFIX "setSum(" << sum << ") called!" << endl;
#endif
if (sum > 0){
i->sum = sum;
}
else {
// error, throw exception
#ifdef DEBUG
clog << DEBUG_PREFIX "invalid argument: " << sum << endl;
#endif
throw invalid_argument("Sum must be positive!");
}
setDate();
}
void Expense::setDate(){
#ifdef DEBUG
clog << DEBUG_PREFIX "setDate() called!" << endl;
#endif
i->date = currentDate(); // currentDate function is in Source.hpp file
assert(date != ""); // assure that setter works
}
// Getters
int Expense::getSum(){
return i->sum;
}
string Expense::getDate(){
return i->date;
}
string Expense::toString() const{
stringstream ss;
ss << i->sum << endl;
return ss.str();
}
}
问题是我无法在实现文件变量 sum 和 date 中达到(也就是内部类中的变量)。我创建了指向内部函数的指针并声明我正在尝试从内部类 ( i->date
, i->sum
) 获取信息,但这没有帮助。我错过了一些东西。也许你能发现问题?谢谢。