【发布时间】:2018-06-30 18:05:43
【问题描述】:
我正在阅读 C++ Primer,但我被困在了
7.3.4。重温友谊让会员功能成为朋友
练习 7.32:定义自己的 Screen 和 Window_mgr 版本,其中 clear 是 Window_mgr 的成员和 Screen 的朋友
我找到了几个已解决的练习,但只在一个文件中:
#include <iostream>
#include <string>
#include <vector>
using std::cin;
using std::cout;
using std::string;
using std::vector;
using std::ostream;
class Screen;
class Window_mgr{
public:
using ScreenIndex = vector<Screen>::size_type;
void clear(ScreenIndex i);
private:
vector<Screen> screens;
};
class Screen{
friend void Window_mgr::clear(ScreenIndex);
public:
typedef string::size_type pos;
Screen(pos ht, pos wd, char c) : height(ht), width(wd), contents(ht * wd, c) {}
private:
pos cursor = 0;
pos height = 0, width = 0;
string contents;
};
void Window_mgr::clear(ScreenIndex i){
Screen &s = screens[i];
s.contents = string(s.height * s.width, ' ');
}
int main(){
Window_mgr var;
return 0;
}
我试图在 5 个单独的文件中解决它,分别是 main.cpp、Window_mgr.h、Window_mgr.cpp、Screen.h 和 Screen.cpp;仍然没有运气。 我在stackoverflow中研究了这个练习,我发现了很多,但是关于在单独的文件中编译它的任何东西,所以我在想......
朋友的成员函数必须在同一个文件中编译?
如果没有
如何在它自己的文件中分离每个类来分离实现和接口?
- main.cpp
- Screen.h/Screen.cpp
- Window_mgr.h/Window_mgr.cpp
和
可选:这 5 个文件必须按什么顺序(如何)在
makefile中编译
这可能吗? 谢谢!
【问题讨论】:
-
Friend成员函数必须编译在同一个文件中?不。
标签: c++ makefile friend friend-function