String function does not return

时间:2016-01-24 17:12:45

标签: c++ class oop

I've written a piece of code. There's a class Rational with numerator and denominator as its private members. Now there is a method toString() which should return the rational number as a string ("numerator/denominator"). For unknown reasons to me, it does not return anything. The code:

#include <iostream>
#include <iomanip>
#include <string>
#include <sstream>

using namespace std;

class Rational {
    long int n, d;
public:
    Rational(long int n, long int d) {
        this->n = n;
        this->d = d;
    }
    bool equals();
    int compareTo();
    std::string toString() {
        string resN, resD;
        string str;
        ostringstream convertN, convertD;
        convertN << this->n;
        convertD << this->d;
        resN = convertN.str();
        resD = convertD.str();

        str = resN + "/" + resD;
        return str;
    }
};

int main() {
    Rational rat(2, 3);
    rat.toString();

    return 0;
}

First I thought something with the conversion algorithm was wrong, and I tried returning anything, but still nothing. Thank you in advance.

2 个答案:

答案 0 :(得分:2)

如果要输出字符串,请使用cout << rat.toString();

答案 1 :(得分:0)

它确实返回了一些东西,你只是没有使用它返回的值。我知道在MATLAB这样的语言中,它可以打印出结果。在这里,你必须自己做。试试这个:

int main() {
    Rational rat(2, 3);
    std::string theString = rat.toString();
    cout << "The result is: " << theString << endl;

    return 0; 
}