0

これが私のコードです。これは私の心を揺さぶっています。

#include <iostream>
#include <sstream>
#include <set>
#include <cmath>
#include <cstdlib>
#include "list.h"
#include "stack.h"
#include <limits>
#define PI 3.1415926535897932384626433832795

class RPN : public Stack<float> {
      public:
             std::string sqrt(float n); 
};

std::string RPN::sqrt(float n){
    std::string x;
    x = sqrt(3.0);
    std::ostringstream ss;
    ss << n;
    return (ss.str());
}

はい、コンパイル中です。sqrt は文字列を返しています。double または float を使用しようとすると、奇妙なエラーがスローされます。誰が何が起こっているのか教えてもらえますか? 私は前にこれを持ったことがない。面白いことに、実際には後で文字列に変換していますが、これが他の場所でコンパイルされるとは思えません...

postfix.cpp: In member function ‘std::string RPN::sqrt(float)’:
postfix.cpp:161:13: error: cannot convert ‘std::string {aka std::basic_string<char>}’ to ‘float’ in assignment

編集: 最初に間違ったコンパイラ エラーを投稿しました。

edit2: 161 行目は n=sqrt(n); double x = sqrt(n) や他の多くの方法も試しました。ああ、上記の方法で返された文字列を出力すると、セグフォルトが発生します(obv ..)

std::string RPN::sqrt(float n) {
    n = sqrt(n);
    std::ostringstream ss;
    ss << n;
    return (ss.str());
}
4

2 に答える 2

3

コードを詳しく見てみましょう

std::string RPN::sqrt(float n){
    std::string x; // temporary string variable

    // calling sqrt with 3.0? What?
    // This call actually would make this function be recursive 
    // (it would hide ::sqrt), making the assignment possible 
    // to compile (as sqrt returns a string)
    // This also means that the function will 
    // eventually cause a stack overflow as there is no break case.
    x = sqrt(3.0); 

    std::ostringstream ss; // temporary string stream
    ss << n; // putting x in the string stream

    // returning the string value of the string stream
    // (i.e. converting x to a string)
    return (ss.str()); 
}

つまり、コンパイル エラーは発生しませんが、そのコードを実行すると実行時エラーが発生します。

編集:

関数はグローバルスコープをマスクするため、定義している独自の関数を呼び出すだけですn = ::sqrt(n)n = std::sqrt(n)#include <cmath>n = sqrt(n)

n = sqrt(n)関数を再帰的にし、コンパイルしません。

于 2013-04-16T11:47:19.560 に答える
3

この行は、文字列を返すメソッドをx = sqrt(3.0);呼び出しています。cmathRDN::sqrt()で関数を呼び出そうとしていると思います。sqrt()メソッドの名前を別のものに変更することをお勧めします。または、電話をかけることもできますstd::sqrt(3.0)

于 2013-04-16T11:47:27.720 に答える