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

时间:2014-04-22 19:52:42

标签: c++

#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})

  3. 如何修复它们?

2 个答案:

答案 0 :(得分:2)

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

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

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

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

答案 1 :(得分:1)

关于第一个错误:

filename = "puz1.txt";

您应该将filename作为参数传递,而不是将其分配到那里。如果您只需要使用"puz1.txt",请使用而不是filename

第二个错误:

Board::fin (filename);

您无法像这样初始化ifstream对象。只需致电open()

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