2016-02-18 146 views
0

我有这两个C++ primer的例子,试图在类定义之外声明一个类成员函数。即使我删除了友谊和定义,第一个也给了我一个错误。第二个工作正常。 任何提示?C++声明类成员以外的类

错误:

src/Screen.h:16:47: error: no ‘void Window_mgr::clear(Window_mgr::ScreenIndex)’ member function declared in class ‘Window_mgr’ 

练习1:

#ifndef SCREEN_H 
#define SCREEN_H 
#include <string> 
#include <vector> 
class Screen; 

class Window_mgr { 

public: 
    using ScreenIndex = std::vector<Screen>::size_type; 
    Window_mgr(); 
private: 
    std::vector<Screen> screens; 
}; 

void Window_mgr::clear(Window_mgr::ScreenIndex); 
class Screen { 

    //friend void Window_mgr::clear(ScreenIndex); 

public: 
    using pos = std::string::size_type; 
    Screen() = default; 
    Screen(pos h, pos w): height(h), width(w), contents(h*w, ' ') { } 
    Screen(pos h, pos w, char c): height(h), width(w), contents(h*w, c) { } 
    char get() const { return contents[cursor]; } 
    inline char get(pos, pos) const; 
    Screen &move(pos, pos); 
    Screen &set(char c) { contents[cursor] = c; return *this; } 
    Screen &set(pos, pos, char); 
    const Screen &display(std::ostream &os) const { do_display(os); return *this; } 
    Screen &display(std::ostream &os) { do_display(os); return *this; } 
    pos size() const; 

private: 
    const void do_display(std::ostream &os) const { os << contents; } 
    pos cursor = 0; 
    pos height = 0, width = 0; 
    std::string contents; 
}; 

inline 
Window_mgr::Window_mgr(): screens{Screen(24, 80, ' ')} { } 

char Screen::get(pos r, pos c) const 
{ pos row = r * width; return contents[row + c]; } 

inline Screen& Screen::move(pos r, pos c) 
{ pos row = r * width; cursor = row + c; return *this; } 

inline Screen& Screen::set(pos r, pos c, char ch) 
{ pos row = r * width; contents[row + c] = ch; return *this; } 

//inline void Window_mgr::clear(ScreenIndex i) 
//{ Screen &s = screens[i]; s.contents = std::string(s.height * s.width, ' '); } 

inline Screen::pos Screen::size() const 
{ return height * width; } 
#endif 

练习2:

#include <iostream> 

int height; 
class Screen { 
public: 
    typedef std::string::size_type pos; 
    void set_height(pos); 
    pos height = 0; 
}; 
Screen::pos verify(Screen::pos); 
//void Screen::set_height(pos var) { height = verify(var); } 

//Screen::pos verify(Screen::pos a) { return a; } 

int main(){ 

    return 0; 
} 

回答

6

不能宣布其类外成员。 你可以定义成员函数以外的类,如果你有声明它里面。第二个例子简单地定义了一个全局函数,验证,它使用来自类Screen的公共类型,但它本身不是Screen的成员。

+0

再次看看代码并记住您的答案,我发现我忘记了第二个示例中的名称空间说明符,因此它将验证函数声明为全局。谢谢! – lmarchesoti

0

无提示可用。

你根本无法做到这一点。

类定义必须是包含在该类中的成员的完整图片。