0

这是我的头文件:

#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) 获取信息,但这没有帮助。我错过了一些东西。也许你能发现问题?谢谢。

4

2 回答 2

2

它们是私人的,而不是公开的。外部类不能访问这个变量(是的,Expenseexternal class这种情况下),你的朋友声明允许访问Inner使用私有数据Expense,但不Expense使用私有数据Inner,这种关系不是传递的。

于 2013-10-30T12:42:39.363 回答
0

你放错了friend,你需要把它放在Inner课堂上。

  class Inner{
     int sum;
     string date;
     friend class Expense;
  };
于 2013-10-30T12:44:10.147 回答