C++ 类作为其他类的成员,如何定义它?

标签 c++ object syntax

为属于另一个类的成员的类编写定义(给定代码,不要问我为什么)。无论如何,我得到一个类型“类”重定义错误,因为我不熟悉 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++ 文件。

关于C++ 类作为其他类的成员,如何定义它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21423349/

相关文章:

java - 如何从 JNI 代码中检测字节顺序?

c++后端使用swig wrapper调用python级别定义的回调

c++ - MPI 代码在超过 2 个节点/进程的最终确定时挂起

带有对象的树的 C# 路径列表

javascript - 在对象数组中的属性中查找具有最大值的所有对象,并从同一对象返回其他属性的值

c++ - 特定资源语言的 LoadAccelerators

python - 对象没有属性-python类执行

syntax - 避免语言细节的混淆

K&R 的 C - 用于声明 - "If expr_1 or expr_3 is omitted, it is simply dropped from the expansion"

ruby - 将错误对象分配给 `rescue` 方法的变量时使用的语法 (=>) 是什么?