C 类是其他类的成员,一个人如何定义这个

C++ class as member of other class, How does one define this?

本文关键字:定义 何定义 一个人 其他 成员      更新时间:2023-10-16

编写是另一个类的成员(给定代码,不要问我为什么)的类的定义。无论如何,我会得到类型的"类"重新定义错误,因为我不熟悉C ,对象的嵌套和预选赛'::'

这是stack.h

    // rest of code above         
    public: // prototypes to be used by the client
   /**  UnderFlow Class
   *    thrown if a pop or top operation would cause the stack to underflow
   */
    class OverFlow
    {
        public:
            /*! @function   OverFlow Constructor
            *   @abstract   constructs the overflow object
            *   @param      string the error message of the overflow exception
            */
            OverFlow(std::string);
            /*! @function   getMessage
            *   @abstract   returns the message containing this exception's error text
            *   @result     string the error message of the overflow exception
            */
            std::string getMessage();
        private:
            std::string message;//error text
    };
    /** UnderFlow Class
    *   thrown if a pop or top operation would cause the stack to underflow
    */
    class UnderFlow
    {
        public:
            /*! @function   UnderFlow Constructor
            *   @abstract   constructs the underflow object
            *   @param      string the error message of the underflow exception
            */
            UnderFlow(std::string);
            /*! @function   getMessage
            *   @abstract   returns the message containing this exception's error text
            *   @result     string the error message of the underflow exception
            */
            std::string getMessage();
    //rest of code below

这是stack.cpp

    //rest of code above
    class stack::OverFlow
    {
string message;
OverFlow::OverFlow()
{
}
OverFlow(string errormessage)
{
    OverFlow::message = errormessage;
}
string OverFlow::getMessage()
{
    return message;
}
};
   class stack::UnderFlow
    {
string message;
UnderFlow::UnderFlow()
{
}
UnderFlow::UnderFlow(string errormessage)
{
    message = errormessage;
}
string UnderFlow::getMessage()
{
    return message;
}

};//rest of code below

我在代码的以下行中获得重新定义错误

class stack::UnderFlow
class stack::OverFlow

我敢肯定这是一个简单的修复,我只是无法实践...

类定义应显示在标题文件中,而不是C 文件中。删除:

class stack::OverFlow
{

来自C 文件。

当前您写了

//rest of code above
class stack::OverFlow
{
string message;
OverFlow::OverFlow()
{
}

stack.cpp文件中。这是在CPP文件中写入类主体的正确性,您应该在标题中进行操作,因此您应该删除

class stack::OverFlow
    {

来自源文件(cpp)。而且您也可以在标题中完成此操作(这是正确的),因此现在您只需要删除上述零件并在cpp中使用正确的名称分辨率添加函数的定义,例如:

stack::OverFlow::OverFlow()  // constructor
{
}
string stack::UnderFlow::getMessage()  // function definition
{
    return message;
}