【发布时间】:2019-11-27 00:15:56
【问题描述】:
更新:感谢您的所有回复,我确实通知了我的教授,他解决了他的问题。再次感谢您的所有帮助!
我把我的类变成了一个模板,然后尝试运行下面的代码,结果却报了三个错误。
sorter.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 以允许代码工作,而不会再次发生错误?
-对不起,因为没有真正解释我的问题是什么。
【问题讨论】:
-
"我需要模板化以下类" - 为什么?那会达到什么目的?你想用模板做什么?您认为它会解决什么问题?请将您的问题缩小到特定问题,并提供足够的详细信息来确定适当的答案。只需在
class声明上方添加template<typename T>即可完成对类的模板化。它不会有用,但会以当前形式回答您的问题。 -
在一个非常基本的级别上坚持
template<typename T>在您的类声明上方,并将int替换为T。 -
当你已经有一个 header 保护时使用
#pragma once是完全多余的。坚持其中任何一个。 (标题保护是可移植的,#pragma是特定于编译器的。) -
错误消息与模板没有任何关系。即使
sorter不是模板,它们也会在那里。你在main中忘记了using namespace std::string_literals;。 -
我已经更新了我的答案以包含一个仅修改
sorter.h的解决方案,但正如我已经说过的那样,这确实是你教授的错误。我会简单地请他们或导师/助理检查他们是否真的打算以这种方式完成作业。