无法访问c ++中的内部类

时间:2013-10-30 12:39:35

标签: c++ class pointers

这是我的头文件:

#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(a.k.a在内部类中的变量)中达不到。我创建了指向内部函数的指针,并声明我正在尝试从内部类(i->datei->sum)获取信息,但这没有用。我错过了什么。也许你能发现问题? 感谢。

2 个答案:

答案 0 :(得分:2)

他们是私人的,不是公开的。外部类无法访问此变量(是的,Expense在这种情况下为external class),您的朋友声明可以访问Inner以使用Expense的私有数据,但是不Expense使用Inner的私人数据,此关系不具有传递性。

答案 1 :(得分:0)

您错放了friend,您需要将其放入Inner课程。

  class Inner{
     int sum;
     string date;
     friend class Expense;
  };