简体   繁体   中英

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");
}

This is my cpp file...my hpp file is:

#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

I got the below errors while I compile:

  1. Error at line in cpp filename = "puz1.txt" . and error is:

    const char* shadows a //parameter.

  2. Error at line in cpp Board::fin (filename); and error is:

    no match call to //(std::basic_ifstream})

How do I fix them?

You can only initialize fin in the contructor initialization list. You also need to #include <fstream> . This would work:

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

It is unclear why you are setting filemane to something different to what is passed in the constructor. If you want a default parameter, use

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

About the first error:

filename = "puz1.txt";

You are supposed to pass the filename as an argument, not to assign it there. If you just need to use "puz1.txt" then use than instead of filename .

The second error:

Board::fin (filename);

You can't initialize the ifstream object like that. Simply call open() .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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