簡體   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