c 如何从类类 .h 文件内部识别.cpp中的 UDT 枚举



当我尝试从.cpp文件中调用 .h 文件中的枚举 UDT 月份时,编译器给了我一个错误。我可以在另一个文件中使用我的枚举 UDT 吗?如果是这样,怎么办?

我的约会。

class Date 
{
public:
    enum Month
        {
        jan = 1, 
        feb, 
        mar, 
        apr, 
        may, 
        jun, 
        jul, 
        aug, 
        sep, 
        oct, 
        nov, 
        dec
        };
    Month int_to_month(int x);
    Date(int y, Month m, int d);
    Month month () const;
...other code

};

编译器突出显示以下对 Month 和 date.cpp 文件中的函数名称的引用的错误

#include "lib.h"
#include "date.h"
Month Date::month () const  
    {
    return m;
    }
Month Date::int_to_month(int x)
    {
    return m;
    }

您需要指定 Month 的来源,如下所示:

Date::Month Date::month () const { /* ... */ }
Date::Month Date::int_to_month(int x) { /* ... */ }

否则,编译器不知道 Month 是什么,它会在全局范围内查找具有该名称的内容。

Month的类型应该是Date::Month的,因为enum是类的成员。如果您希望它是直Month,请在文件范围内声明它。

最新更新