简体   繁体   English

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

[英]C++ I keep getting “was not declared in this scope error”

So, I have a header file and a class file. 所以,我有一个头文件和一个类文件。 But when I compile puzzle.cpp , I keep getting get_solution was not declared in this scope. 但是当我编译puzzle.cpp ,我一直没有在这个范围内声明get_solution I don't get why that error occurs since its inside the same class so I can call any function inside the same class. 我不明白为什么会发生错误,因为它在同一个类中,所以我可以在同一个类中调用任何函数。 Can anyone please help me on this? 有人可以帮我这个吗? Thanks! 谢谢!

puzzle.h 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 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 "";
}

It looks like you've forgotten to make solve and to_string member functions: 它看起来像你忘了做solveto_string成员函数:

Change 更改

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

To

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

Your function bool solve(string proposed_solution) does not define a member function of puzzle but a "plain" function; 你的函数bool solve(string proposed_solution)没有定义puzzle的成员函数,而是一个“普通”函数; Hence, get_solution(); 因此, get_solution(); within its body is not recognized as a member of puzzle , too. 在它的身体内也不被认为是puzzle一员。 You'll have to write bool puzzle::solve(string proposed_solution) { ... and it should work. 你将不得不写bool puzzle::solve(string proposed_solution) { ...它应该有效。

solve and to_string are supposed to be methods, so you need to prefix them with the class' name followed by two colons (ie, puzzle:: ): solveto_string应该是方法,所以你需要在它们前面添加类名称后跟两个冒号(即puzzle:: :):

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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