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