问题描述
本学期我正在学习C ++(刚刚学习Java),并使用Codewars进行一些C ++编码练习(这是我最有效的练习方法,但只需要方法而不是驱动程序),但不确定如何为该方法创建驱动程序,以便我可以在IDE中进行练习。
我主要在这里缺少什么,因此它可以在我的IDE中运行?解决方案(不是我的代码)有效,但是我的主要方法无法驱动它。
#include <iostream>
#include <cctype>
#include <unordered_set>
int main(int argc,char *argv[]) {
using namespace std;
cout << is_isogram("Dermatoglyphics"); //error: use of undeclared identifier 'is_isogram'
}
bool is_isogram(std::string str) { //warning: Function is never used
std::unordered_set<char> char_set;
for (const auto &c : str) {
auto c_lower = std::tolower(c);
if (char_set.count(c_lower) == 0) char_set.insert(c_lower);
else return false;
}
return true;
}
解决方法
在is_isogram()
中尝试使用 main()
时,它实际上尚未被声明,因此“使用未声明的标识符” ( a)。
您可以通过以下两种方法之一解决此问题,第一种方法是在使用前通过函数原型对其进行声明,例如:
bool is_isogram(std::string); # declare
int main(int argc,char *argv[]) { # define
// main stuff
}
bool is_isogram(std::string str) { # define
// is_isogram stuff
}
第二种方法是交换is_isogram()
和main()
,使声明作为定义的一部分完成(定义隐式声明的内容):
bool is_isogram(std::string str) { # define
// is_isogram stuff
}
int main(int argc,char *argv[]) { # define
// main stuff
}
(a)报告的第二个问题“功能未使用”几乎可以肯定是第一个问题的副作用。由于编译器无法通过is_isogram()
进行main()
调用,因此在报告错误后将其丢弃。结果,现在没有代码在定义函数时调用您的函数。