包含标头时,'operator Apple'不是可识别的运算符或类型

'operator Apple' is not a recognized operator or type when including a header

本文关键字:识别 类型 运算符 Apple operator 包含标      更新时间:2023-10-16

我会简短的。

我有 2 个类:AppleOrange ,如下所示:

Apple.h(Apple.c为空白(

#ifndef APPLE_H_
#define APPLE_H_
class Apple {};
#endif /* APPLE_H_ */

Orange.h

#ifndef ORANGE_H_
#define ORANGE_H_
#include "Apple.h"
class Orange {
public:
    Orange();
    virtual ~Orange();
    operator Apple ();
};
#endif /* ORANGE_H_ */

Orange.cpp

#include "Orange.h"
Orange::Orange() {
    // TODO Auto-generated constructor stub
}
Orange::~Orange() {
    // TODO Auto-generated destructor stub
}
Orange::operator Apple() {
    Apple y;
    return y;
}

因为这些,这些都很棒。

但是当我#include "Orange.h"添加到Apple.h时,我得到'operator Apple' is not a recognized operator or type错误。

如下:

#ifndef APPLE_H_
#define APPLE_H_
#include "Orange.h"
class Apple {};
#endif /* APPLE_H_ */

#include "Orange.h"制造的问题是什么?

这是因为你现在有一个循环依赖:Orange.h取决于Apple.h,这取决于Orange.h等。

Orange.h头文件中,声明 Apple 类可能就足够了:

// Tell the compiler that there is a class named `Apple`
class Apple;
class Orange {
public:
    Orange();
    virtual ~Orange();
    operator Apple ();
};

然后在Orange.cpp源文件中包括Apple.h头文件。