繁体   English   中英

C ++在类外部声明类成员

[英]c++ declaring class member outside class

我有两个来自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;
}

您不能在其类之外声明成员。 如果在内部声明了成员函数,则可以在其外部定义它。 第二个示例仅定义一个全局函数verify ,它使用Screen类中的公共类型,但它本身不是Screen的成员。

无提示。

您根本无法做到这一点。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM