为什么转发声明不起作用?我没有在构造函数中实现任何指针,所以它应该可以工作。那为什么不呢?
#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
类的完整定义。
关于c++ - 为什么这段代码不起作用?我收到错误 : incomplete type or does not name a type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51964931/