我最近惊讶地发现这段代码可以编译(至少在 gcc 和 MSVC++ 上):
template<typename T>
class A {
public:
T getT() { return T(); }
};
class B : public A<B> { };
Run Code Online (Sandbox Code Playgroud)
当这没有发生时:
class A;
class B : public A { };
class A {
public:
B getB() { return B(); }
};
Run Code Online (Sandbox Code Playgroud)
对我来说,模板类可以采用不完整的类型作为模板参数,并且有一个函数通过调用其构造函数返回一个类型,并且仍然可以编译,这对我来说似乎很奇怪。那么到底哪里需要完整的类型(或者如果列表更短,哪里不需要它们)?
链接到我的上一个主题: C++类前向声明
现在主要的事情:
我决定将所有返回的类型更改为指针以避免内存泄漏,但现在我得到了:
27 C:\Dev-Cpp\Projektyyy\strategy\Tiles.h ISO C++ forbids declaration of `tile' with no type
27 C:\Dev-Cpp\Projektyyy\strategy\Tiles.h expected `;' before "tick"
Run Code Online (Sandbox Code Playgroud)
它只在基类中,其他一切都没问题... tile类中返回*tile的每个函数都有这个错误...
一些代码:
class tile
{
public:
double health;
tile_type type;
*tile takeDamage(int ammount) {return this;};
*tile onDestroy() {return this;};
*tile onUse() {return this;};
*tile tick() {return this};
virtual void onCreate() {};
};
Run Code Online (Sandbox Code Playgroud)