const char*在构造函数中的用法

const char* usage in constructor

本文关键字:用法 构造函数 char const      更新时间:2023-10-16
#include "Board.hpp"
#include <iostream>
using namespace std;
Board::Board (const char* filename){
  filename = "puz1.txt";
  Board::fin (filename);
  if(!fin) fatal("Error in opening the file");
}

这是我的cpp文件。。。我的hpp文件是:

#ifndef BOARD_H
#define BOARD_H
#include <iostream>
using namespace std;
#include "tools.hpp"
#include "square.hpp"
class Board {
private:
    SqState bd[81];
    ifstream fin;
public:
    Board(const char* );
    ostream& print(ostream& );
};
inline ostream& operator <<(ostream& out, Board& b) { return b.print(out);}
#endif //Board.hpp

我在编译时出现了以下错误:

  1. cpp filename = "puz1.txt"中的行出现错误。错误为:

    const char*对//参数进行阴影处理。

  2. cpp Board::fin (filename);中的行出错错误为:

    对//(std::basic_ifstream}(的无匹配调用

我该如何修复它们?

您只能在构造函数初始化列表中初始化fin。您还需要#include <fstream>。这将起作用:

Board::Board (const char* filename): fin(filename)
{
  ....
}

目前还不清楚为什么要将filemane设置为与构造函数中传递的内容不同的内容。如果您想要一个默认参数,请使用

Board::Board (const char* filename="puz1.txt"): fin(filename) {}

关于第一个错误:

filename = "puz1.txt";

您应该将filename作为参数传递,而不是将其分配给它。如果您只需要使用"puz1.txt",则使用than而不是filename

第二个错误:

Board::fin (filename);

不能像那样初始化ifstream对象。只需拨打open()即可。

fin.open("puz1.txt");
if(fin.is_open()) // you can pass additional flags as the second param
{
}