标准函数和操作在类构造函数中不起作用

Standard functions and operations not working in class constructor

本文关键字:构造函数 不起作用 函数 操作 标准      更新时间:2023-10-16

我正在尝试使用构造函数制作我的第一个类,但它似乎表现得很奇怪。我的类派生自filebuf,由于某种原因,我无法在构造函数中打开它。我尝试添加用于调试的 cout 语句,但无法识别<<运算符。

#include <iostream>
#include "bin.h"
int main()
{
    bin myBin("e:Temptest.txt");

    system("PAUSE");
    return 0;
}

宾·

#pragma once
#include <fstream>
#include <cstdlib>
#include <cstring>
class bin : private std::filebuf {
int buffSize = 1000;
char* buffer;
unsigned int length;
short int buffCounter;
public:
    bin(std::string fileName)
    {
        open(fileName.c_str(), std::ios::in | std::ios::out | std::ios::trunc);
        if (!is_open())
            std::cout << "ERROR: failed to open file " << fileName << std::endl;
        //set all IO operations to be unbufferred, buffering will be managed manually
        setbuf(0, 0);
        //create buffer
        buffer = new char[buffSize];
    };

     virtual ~bin()
    {
        delete buffer;
    };
};
bin myBin("e:Temptest.txt");

您必须按如下方式更正上述行:

bin myBin("e:\Temp\test.txt");

演示:http://cpp.sh/7b4k

看起来你需要:

#include <iostream>

要使用std::string您需要:

#include <string>

包含iostream可能有前向声明的std::string但没有完整的定义,你不会得到operator<<(或c_str())。

其他一些回答者可能无法重现您的问题,因为不同的标准库可能iostream完全#include <string>(这是允许的,但不是必需的)。

std::cout << "ERROR: failed to open file " << fileName << std::endl;

应该是

std::cout << "ERROR: failed to open file " << fileName.c_str() << std::endl;

std::cout并不总是接受std::string但确实接受const char *