繁体   English   中英

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

[英]const char* usage in constructor

#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);中的行错误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
{
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM