CrossoverC 2016-06-02 03:19 采纳率: 33.3%
浏览 1206
已采纳

C++ primer 中的一个关于友元例子,在vs2015中报错

定义了两个类Screen和window-mgr,window-mgr作为Screen的友元,但是提示Screen没有构造函数

 #include <iostream>
#include <string>
#include "Window_mgr.h"

using namespace std;

class Screen {
    friend class Window_mgr;
public:
    typedef string::size_type pos;
    Screen(pos ht, pos wd, char c) :height(ht), width(wd), contents(ht*wd, c) {}
    Screen() = default;

    char get()const
    {
        return contents[cursor];
    }
    inline char get(pos ht, pos wd)const;
    Screen &move(pos r, pos c);
    void some_memeber()const;
    Screen &set(char);
    Screen &set(pos, pos, char);
    Screen &display(ostream &os)
    {
        do_display(os);
        return *this;
    };
    const Screen &display(ostream &os)const
    {
        do_display(os);
        return *this;
    }
private:
    pos cursor = 0;
    pos height = 0, width = 0;
    string contents;
    mutable size_t access_ctr;
    void do_display(ostream &os)const { os << contents; }
};

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

}

inline Screen &Screen::set(char c)
{
    contents[cursor] = c;
    return *this;


}
inline Screen &Screen::set(pos r, pos col, char ch)
{
    contents[r*width + col] = ch;
    return *this;
}
  #include <iostream>
#include <vector>
#include <string>
#include "Screen.h"
class Screen;


using namespace std;

class Window_mgr
{

public:

    using ScreenIndex = vector< Screen>::size_type;
    void clear(ScreenIndex);


private:
    vector<Screen> screens{ Screen(20, 40, 'x') };/**/报错,提示Screen类没有构造函数**

};
  • 写回答

2条回答 默认 最新

  • Valtava 2016-06-02 05:15
    关注

    我没看错的话,你是在两个头文件互相包含并且没有用#ifndef之类的防止重复包含的措施?

    包含头文件的意思是把整个头文件复制到 #include这一行,你这种情况不,A包含B,B包含A,A又包含B,不就是无限循环了么。。

    只是声明友元,没必要包含头文件,加上#ifndef之类的句子,然后直接注释掉#include "Window_mgr.h" 这句再试试

    另外,类的成员提供默认值(Window_mgr里的screens)这一点,因为没用过VS2015,不知道是不是支持,至少VS2015之前的任何版本(比如VS2013)都不支持。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况
  • ¥15 画两个图 python或R
  • ¥15 在线请求openmv与pixhawk 实现实时目标跟踪的具体通讯方法
  • ¥15 八路抢答器设计出现故障
  • ¥15 opencv 无法读取视频
  • ¥15 按键修改电子时钟,C51单片机
  • ¥60 Java中实现如何实现张量类,并用于图像处理(不运用其他科学计算库和图像处理库))
  • ¥20 5037端口被adb自己占了
  • ¥15 python:excel数据写入多个对应word文档