一个班级内的结构

时间:2014-03-03 14:29:39

标签: c++ class structure

我有一个私有的结构类。 如何访问该结构的数据成员?

  class ClassStruct
  {
  private:
     struct Struct
     {
        std::string time;
        int temp;
     };
  public:
     ClassStruct();
  };

以下是我的尝试:

struct Struct o;
ClassStruct object;
cout << "Enter time (hh:mm): ";
cin >> object.o.time;

但它在“o”上显示错误。

2 个答案:

答案 0 :(得分:5)

您只能在声明的类实现中访问此结构。在您的示例中,您可以访问它的唯一位置是ClassStruct

的构造函数

编辑试图解释人们在问你什么:

在ClassStruct.h中:

class ClassStruct
{
private:
   struct Struct
   {
      std::string time;
      int temp;
   };
public:
   ClassStruct();
   void test(){
     Struct good; // This will work.
     good.temp = 5;
   }
};

在ClassStruct.cpp中

ClassStruct::ClassStruct(){
   Struct alsoGood;
   std::cout << "Also Good Here" << std::endl;
}

void nonClassFunction(){
  ClassStruct::Struct bad; // compiler error
}

在AnyOther.cpp

void wontWork(){
  ClassStruct::Struct alsoBad; // compiler error.
}

答案 1 :(得分:2)

要访问结构的数据成员,您需要定义此结构的对象。您可以将此结构的对象定义为封闭类的数据成员,或者作为在类的方法中创建的对象。

例如

  class ClassStruct
  {
  private:
     struct Struct
     {
        std::string time;
        int temp;
     } obj1;
  public:
     ClassStruct();
     void SomeMethod()
     {
        Struct obj2;
        // some operations with obj2
     }

  };