为什么此代码不起作用?我收到一个错误:类型不完整或未命名类型

时间:2018-08-22 10:34:32

标签: c++ forward-declaration

为什么转发声明无效?我没有在构造函数中实现任何指针,因此它应该可以工作。那为什么不呢?

#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 ++中实现状态模式,但我不明白这些指针的工作原理。

with

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 );
                            ^

1 个答案:

答案 0 :(得分:2)

要创建类的实例(就像对new on进行操作一样),您需要 full 定义。但是到那时,在源代码中您还没有类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类的完整定义。