2016-02-18 155 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

無提示可用。

你根本無法做到這一點。

類定義必須是包含在該類中的成員的完整圖片。