更新:感谢您的所有回复,我确实通知了我的教授,他解决了他这边的问题。再次感谢您的帮助!!
我把我的类变成了一个模板,并尝试运行下面的代码,只得到三个错误。
排序器.h
#pragma once
#ifndef SORT_THINGS
#define SORT_THINGS
#include <utility>
template <typename T>
class sorter {
public:
sorter(T a,T b,T c): _a{a}, _b{b}, _c{c} {
using std::swap;
if (_a > _b) { swap (_a, _b); }
if (_b > _c) { swap (_b, _c); }
if (_a > _b) { swap (_a, _b); }
}
const T& a() const { return _a; }
const T& b() const { return _b; }
const T& c() const { return _c; }
private:
T _a, _b, _c;
};
#endif
tests.cpp(无法编辑 tests.cpp 文件,教授创建了这个文件并锁定了编辑)
#include <iostream>
#include "sorter.h"
template <typename T>
void test_sort(std::istream& in, std::ostream& out)
{
T a, b, c;
in >> a >> b >> c;
sorter<T> s {a, b, c};
out << s.a() << ' ' << s.b() << ' ' << s.c();
}
int main(int, char* argv[])
{
using namespace std;
if (argv[2] == "int"s) {
test_sort<int>(cin, cout);
} else if (argv[2] == "char"s) {
test_sort<char>(cin, cout);
} else if (argv[2] == "string"s) {
test_sort<std::string>(cin, cout);
} else {
cerr << "ungecognized test type.\n";
return 1;
}
return 0;
}
错误:
./tests.cpp:17:20: error: unable to find string literal operator 'operator""s' with 'const char [4]', 'long unsigned int' arguments
if (argv[2] == "int"s) {
./tests.cpp:19:27: error: unable to find string literal operator 'operator""s' with 'const char [5]', 'long unsigned int' arguments
} else if (argv[2] == "char"s) {
./tests.cpp:21:27: error: unable to find string literal operator 'operator""s' with 'const char [7]', 'long unsigned int' arguments
} else if (argv[2] == "string"s) {
问题:我是否应该更改 sorter.h 以允许代码正常工作,而不会再次出现错误?
-抱歉,没有真正解释我的问题是什么。
最佳答案
您打算与 s
一起使用的字符串文字运算符在字符串文字之后,例如这里:
if (argv[2] == "int"s)
在 std::literals::string_literals
中定义.它需要导入到当前上下文中,以便通过非限定名称查找找到它。
通常这是通过 using namespace std::string_literals;
完成的在使用运算符的适当范围内。以 using namespace std;
为例在你的代码中,它应该放在 main
中:
int main(int, char* argv[])
{
using namespace std;
using namespace std::string_literals;
...
您的问题表明您不应该更改 main
.在那种情况下,无论是谁给您分配的,这都是一个明显的错误。
如果你真的想让这个在这个特定的实例中工作,只修改 sorter.h
, 那么你也可以加上using namespace std::string_literals;
在 #include <utility>
之后.然而,放置 using namespace
被认为是不好的风格。头文件中的语句,因为它以不受控制的方式将名称引入所有使用头文件的翻译单元的全局命名空间,不应这样做。
这里的错误是你的教授犯了一个简单的错误,他们很容易修复。
关于c++ - 将 C++ 类更改为模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59061263/