[英]Why doesn't this code work? I got an error: incomplete type or does not name a type
为什么转发声明不起作用? 我没有在构造函数中实现任何指针,因此它应该可以工作。 那为什么不呢?
#include<iostream>
using namespace std;
class foo;
/*if i use this 2 lines i got first error if not the second one. How do i solve this? */
class on;
class off;
class state{
protected:
foo *_context;
public:
virtual void t_on() = 0;
virtual void t_off() = 0;
virtual void handle() = 0;
};
class foo{
private:
state *_current;
public:
void setState( state* st){
_current = st;
}
void on(){
_current->t_on();
}
void off(){
_current->t_off();
}
void handle(){
_current->handle();
}
};
class off:public state{
void t_on(){
std::cout << "on\n";
}
void t_off(){
std::cout << "cant is off\n";
}
void handle(){
std::cout << "handle to on";
_context->setState( new on );
}
};
class on:public state{
public:
void t_on(){
std::cout << "cant is on\n";
}
void t_off(){
std::cout << "off\n";
}
void handle(){
std::cout << "handle to off";
_context->setState( new off );
}
};
int main ()
{
foo asd;
asd.setState(new on);
asd.on();
asd.off();
return 0;
}
我试图在C ++中实现状态模式,但是我不明白这些指针是如何工作的。
class on;
class off;
当我尝试使用前向声明时,就会发生这种情况。
main.cpp: In member function 'virtual void off::handle()':
main.cpp:45:28: error: invalid use of incomplete type 'class on'
_context->setState( new on );
^
main.cpp:6:8: note: forward declaration of 'class on'
class on;
如果我在上课时遇到此错误,那么为什么上课不起作用?
当我现在
main.cpp: In member function 'virtual void off::handle()':
main.cpp:53:28: error: 'on' does not name a type
_context->setState( new on );
^
要创建一个类的实例(就像您对new on
),您需要完整的定义。 但在源代码这一点你不用类的完整定义on
,只有向前声明。
常见的解决方案是将类分为类定义和成员函数定义。
像例如
// Define the class
class off:public state{
public:
void t_on();
void t_off();
void handle();
};
// Define the class and its member functions
class on:public state{
public:
void t_on(){
std::cout << "cant is on\n";
}
void t_off(){
std::cout << "off\n";
}
void handle(){
std::cout << "handle to off";
_context->setState( new off ); // Can use off because it's fully defined
}
};
// Define the member function of the class off
inline void off::t_on(){
std::cout << "on\n";
}
inline void off::t_off(){
std::cout << "cant is off\n";
}
inline void off::handle(){
std::cout << "handle to on";
_context->setState( new on ); // Can use on because it's fully defined
}
使用上面的代码,当定义了类on
及其成员函数时,将完全定义类off
。 然后,稍后在定义off
的成员函数时,您还将具有on
类的完整定义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.