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

标签 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* shadows a //parameter.

  2. cpp Board::fin (filename); 中的一行错误 错误是:

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

我该如何修复它们?

最佳答案

只能初始化fin在构造函数初始化列表中。您还需要 #include <fstream> .这会起作用:

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

不清楚为什么要设置 filemane与构造函数中传递的内容不同。如果你想要一个默认参数,使用

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

关于c++ - const char* 在构造函数中的用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23228905/

相关文章:

c++ - 更好地使用openmp

c++ - 如何在字符串中使用编译时常量 __LINE__?

c++ - 使用opengl和c++使用动画(经过一段时间后一个一个地)翻译三角形

c++ - 如何获取正确的线程 ID 和值

c++ - 解释 static_cast "static_cast<void (Pet::*)(int)>"语法?

c++ - 为什么 printf 在打印十六进制时只打印一个字节?

c++ - Qt:为项目资源中的 .txt 文件打开的 QFile 的空内容

c++ - 使用 Visual Studio 2013 的自定义编译器

c++ - 如何将 bsoncxx::document::element 写入控制台

c++ - 传递变量时 QTimer 不会启动