error: must use ‘class’ tag to refer to type ‘XXX’ in this scope
开发环境: Qt Creator 4.8.2
在写程序的时候,遇到了编译器报错
error: must use ‘class’ tag to refer to type ‘XXX’ in this scope
出错的代码部分如下:
Iterator* ConcreteAggregate::ConcreteIteratorDesc()
{
return new ConcreteIteratorDesc(this); //error: must use 'class' tag to refer to type 'ConcreteIteratorDesc' in this scope
}
根据提示,修改代码如下后,编译器错误消失
Iterator* ConcreteAggregate::ConcreteIteratorDesc()
{
// return new ConcreteIteratorDesc(this);
return new class ConcreteIteratorDesc(this);
}
经过排查,终于发现了这个错误的原因,首先定义了一个抽象类及其子类
class Aggregate
{
public:
virtual Iterator* CreateIterator() = 0;
virtual Iterator* ConcreteIteratorDesc() = 0;
virtual vector<object>* GetVector() = 0;
};
//定义一个具体的聚合类
class ConcreteAggregate : public Aggregate
{
public:
ConcreteAggregate();
~ConcreteAggregate();
Iterator* CreateIterator() override;
Iterator* ConcreteIteratorDesc() override;
int GetCount() const;
vector<object>* GetVector() override;
object GetElement(int index);
private:
vector<object>* items;
};
然后又定义了一个类
//实现从前向后的迭代器
class ConcreteIterator : public Iterator
{
public:
//初始化时将具体的聚合对象传入
ConcreteIterator(Aggregate* aggregate);
object First() override;
object Next() override;
object CurrentItem() override;
bool IsDone() override;
private:
ConcreteAggregate* m_aggregate; //定义了一个具体聚集对象
int current;
};
注意看可以发现,新定义的类名为ConcreteIterator,而Aggregate类中有同名的函数
virtual Iterator* ConcreteIteratorDesc() = 0;
在实现子类ConcreteAggregate的ConcreteIteratorDesc()函数时,编译器报错
Iterator* ConcreteAggregate::ConcreteIteratorDesc()
{
return new ConcreteIteratorDesc(this);
// return new class ConcreteIteratorDesc(this);
}
解决方案:
- 一种解决办法是在类前面加class,告诉编译器,调用关键字的位置是一个类
Iterator* ConcreteAggregate::ConcreteIteratorDesc()
{
return new class ConcreteIteratorDesc(this);
}
- 另一种解决办法就是更换关键字
参考资料:
1 https://blog.csdn.net/fjjaylz/article/details/88744885 关于C++中class关键字的一种特别使用情况