C ++我一直得到“未在此范围内声明错误”

时间:2018-02-07 20:03:32

标签: c++

所以,我有一个头文件和一个类文件。但是当我编译puzzle.cpp时,我不断在此范围内声明get_solution。我不明白为什么会发生错误,因为它在同一个类中,所以我可以在同一个类中调用任何函数。有人可以帮我这个吗?谢谢!

puzzle.h

#ifndef PUZZLE_H
#define PUZZLE_H

#include<iostream>
#include <string>
#include <vector>

class puzzle{
private:
    std::string _solution;
    std::vector<bool> _guesses;
public:
    puzzle(std::string solution);
    std::string get_solution(){return _solution;}
    bool guess(char c);
    bool solve(std::string proposed_solution);
    std::string to_string();
};

#endif

puzzle.cpp

#include <iostream>
#include "puzzle.h"
#include <string>
#include <vector>

using namespace std;

puzzle::puzzle(std::string solution) {
    _solution = solution;
   for(int i = 0; i < 256; i++)
      _guesses.push_back(false);
}

bool puzzle::guess(char c){
    int num = c;
    if(c<='z' || c>='a')
        if(_guesses.at(c) == false){
          _guesses.at(c) == true;
           return true;
       }
    return false;
}

bool solve(string proposed_solution){
    string test = get_solution();
    if(proposed_solution.compare(test) == 0)
       return true;
    return false;
}

string to_string(){
   int len = get_solution().length();
   return "";
}

3 个答案:

答案 0 :(得分:3)

您似乎忘记了solveto_string成员函数:

更改

string to_string(){ ...
bool solve(string proposed_solution){ ...
    ^^^

string puzzle::to_string(){ ...
bool puzzle::solve(string proposed_solution){ ...

答案 1 :(得分:2)

您的函数bool solve(string proposed_solution)未定义puzzle的成员函数,而是定义&#34; plain&#34;功能;因此,其身体内的get_solution();也未被识别为puzzle的成员。你必须写bool puzzle::solve(string proposed_solution) { ...,它应该有效。

答案 2 :(得分:2)

solveto_string应该是方法,因此您需要在其前面添加类名称后跟两个冒号(即puzzle::):

bool puzzle::solve(string proposed_solution){
    // Code ...
}

string puzzle::to_string(){
    // Code ...
}