我有来自c ++ primer的这两个例子,试图在类定义之外声明一个类成员函数。即使我删除了友谊和定义,第一个给我一个错误。第二个工作正常。 任何提示?
错误:
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;
}
答案 0 :(得分:6)
您不能在其类之外声明成员。 如果您在内部声明,则可以定义类之外的成员函数。第二个示例只是定义一个全局函数 verify ,它使用Screen类中的公共类型,但它本身不是Screen的成员。
答案 1 :(得分:0)
没有提示。
你根本做不到。
类定义必须是该类中包含的成员的完整图片。