[英]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: 这是我的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
I got the below errors while I compile: 编译时出现以下错误:
Error at line in cpp filename = "puz1.txt"
. cpp filename = "puz1.txt"
中的行错误。 and error is: 错误是:
const char* shadows a //parameter. const char *阴影//参数。
Error at line in cpp Board::fin (filename);
cpp Board::fin (filename);
中的行错误Board::fin (filename);
and error is: 错误是:
no match call to //(std::basic_ifstream}) 没有匹配调用///(std :: basic_ifstream})
How do I fix them? 我该如何解决?
You can only initialize fin
in the contructor initialization list. 您只能在构造器初始化列表中初始化fin
。 You also need to #include <fstream>
. 您还需要#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. 目前尚不清楚为什么将filemane
设置为与构造函数中传递的不同。 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. 您应该将filename
作为参数传递,而不是在此处分配。 If you just need to use "puz1.txt"
then use than instead of filename
. 如果只需要使用"puz1.txt"
则使用than代替filename
。
The second error: 第二个错误:
Board::fin (filename);
You can't initialize the ifstream
object like that. 您不能像这样初始化ifstream
对象。 Simply call open()
. 只需调用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.