【发布时间】:2021-06-10 13:49:00
【问题描述】:
我正在尝试为有理数编写一个类。到目前为止,它看起来如下:
#include <iostream>
template <typename T>
class Rational {
public:
Rational();
Rational(T a);
Rational(T a, T b);
std::string to_string();
private:
T num_;
T denom_;
};
Rational::Rational(){
num_ = 0;
denom_ = 1;
}
Rational::Rational(T a){
num_ = a;
denom_ = 1;
}
Rational::Rational(T a, T b) {
num_ = a;
denom_ = b;
}
std::string Rational::to_string() {
return std::to_string(num_) + "/" + std::to_string(denom_);
}
int main() {
typedef Rational<int> R;
R r1, r2(2), r3(3, 4);
std::cout << r1.to_string() + "\n" << r2.to_string() + "\n" << r3.to_string() << std::endl;
return 0;
}
如您所见,我想使用一个模板参数,允许通过以下方式选择数字的类型:
typedef Rational<int> R;
我尝试按照https://riptutorial.com/cplusplus/example/14397/member-types-and-aliases 的说明进行操作,但不幸的是它还没有奏效。我收到以下错误消息:
rational.cpp:25:1: error: 'Rational' is not a class, namespace, or enumeration
Rational::Rational(){
^
rational.cpp:14:7: note: 'Rational' declared here
class Rational {
^
rational.cpp:30:1: error: 'Rational' is not a class, namespace, or enumeration
Rational::Rational(T a){
^
rational.cpp:14:7: note: 'Rational' declared here
class Rational {
^
rational.cpp:30:20: error: unknown type name 'T'
Rational::Rational(T a){
^
rational.cpp:35:1: error: 'Rational' is not a class, namespace, or enumeration
Rational::Rational(T a, T b) {
^
rational.cpp:14:7: note: 'Rational' declared here
class Rational {
^
rational.cpp:35:20: error: unknown type name 'T'
Rational::Rational(T a, T b) {
^
rational.cpp:35:25: error: unknown type name 'T'
Rational::Rational(T a, T b) {
^
rational.cpp:40:13: error: 'Rational' is not a class, namespace, or enumeration
std::string Rational::to_string() {
^
rational.cpp:14:7: note: 'Rational' declared here
class Rational {
^
7 errors generated.
谁能指出我哪里出错了?
【问题讨论】:
-
“它还不能工作”是什么意思?请澄清您面临的问题。
-
您的问题在于方法的定义,缺少
template <typename T>和<T>Fixed code。 -
rational.cpp?似乎这将是接下来要解决的问题:stackoverflow.com/questions/495021/… -
这至少是您最近提出的关于类模板的第二个问题。虽然每个问题都有规范的目标,但请注意,您没有从外部资源中学习,是在浪费其他用户的时间。我强烈建议尝试理解这些概念,并且仅在您尝试解决问题一段时间后才提出问题。 SO 并不是一个真正的教程网站,因此使用它并不适合您。