详解C++编程中的嵌套类的声明与其中的函数使用

2020-01-06 14:28:41王旭


// member_functions_in_nested_classes.cpp
class BufferedIO
{
public:
  enum IOError { None, Access, General };
  class BufferedInput
  {
  public:
    int read(); // Declare but do not define member
    int good(); // functions read and good.
  private:
    IOError _inputerror;
  };

  class BufferedOutput
  {
    // Member list.
  };
};
// Define member functions read and good in
// file scope.
int BufferedIO::BufferedInput::read()
{
  return(1);
}

int BufferedIO::BufferedInput::good()
{
  return _inputerror == None;
}
int main()
{
}

在前面的示例中,qualified-type-name 语法用于声明函数名称。声明:


BufferedIO::BufferedInput::read()

表示“作为 read 类(位于 BufferedInput 类的范围中)的成员的 BufferedIO 函数。” 由于此声明使用 qualified-type-name 语法,因此以下形式的构造是可能的:


typedef BufferedIO::BufferedInput BIO_INPUT;

int BIO_INPUT::read()

上述声明与前一个声明等效,但它使用了 typedef 名称来代替类名称。
嵌套类中的友元函数
嵌套类中声明的友元函数被认为是在嵌套类而不是封闭类的范围内。因此,友元函数未获得对封闭类的成员或成员函数的特定访问权限。如果需要使用在友元函数中的嵌套类中声明的名称,并且友元函数是在文件范围内定义的,请使用限定的类型名称,如下所示:


// friend_functions_and_nested_classes.cpp

#include <string.h>

enum
{
  sizeOfMessage = 255
};

char *rgszMessage[sizeOfMessage];

class BufferedIO
{
public:
  class BufferedInput
  {
  public:
    friend int GetExtendedErrorStatus();
    static char *message;
    static int messageSize;
    int iMsgNo;
  };
};

char *BufferedIO::BufferedInput::message;
int BufferedIO::BufferedInput::messageSize;

int GetExtendedErrorStatus()
{
  int iMsgNo = 1; // assign arbitrary value as message number

  strcpy_s( BufferedIO::BufferedInput::message,
       BufferedIO::BufferedInput::messageSize,
       rgszMessage[iMsgNo] );

  return iMsgNo;
}

int main()
{
}

以下代码演示声明为友元函数的函数 GetExtendedErrorStatus。在文件范围内定义的函数中,将消息从静态数组复制到类成员中。请注意,GetExtendedErrorStatus 的更佳实现是将其声明为:


int GetExtendedErrorStatus( char *message )

利用前面的接口,许多类可以通过传递要复制错误消息的内存位置来使用此函数的服务。



注:相关教程知识阅读请移步到C++教程频道。