I am trying to write a class for rational numbers. So far it looks as follows:
#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;
}
As you can see, I want to use a template parameter that allows to choose the type of the numbers via:
typedef Rational<int> R;
I tried to follow the instructions from https://riptutorial.com/cplusplus/example/14397/member-types-and-aliases, but unfortunately it doesn't work yet. I get the following error message:
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.
Can anyone point out, where I am going wrong?