[英]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: 它看起来像你忘了做
solve
和to_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::
): solve
和to_string
应该是方法,所以你需要在它们前面添加类名称后跟两个冒号(即puzzle::
:):
bool puzzle::solve(string proposed_solution){
// Code ...
}
string puzzle::to_string(){
// Code ...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.