2016-01-24 88 views
-1

我写了一段代码。有一个以分子和分母作为其私人成员的Rational类。现在有一个方法toString(),它应该返回有理数作为一个字符串(“分子/分母”)。对于我来说不明原因,它不会返回任何东西。代码:字符串函数不返回

#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; 
} 

首先我想用的东西转换算法是错误的,我试图返回任何东西,但仍然一无所获。先谢谢你。

+2

它确实返回字符串,然后把它扔掉。 (顺便说一句,比尔希克斯是一个好喜剧演员,而他已经死了,我不认为你是他) –

+0

没有详细的选项:'string toString(){ostringstream s; s << n <<'/'<< d;返回s.str();}'。 – molbdnilo

回答

2

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

0

它返回的东西,你只是不使用它返回的值。我知道像MATLAB这样的语言,它可以打印出结果。在这里,你必须自己做。试试这个:

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

    return 0; 
}