2016-09-26 8 views
1

文字列表現が指定された整数と等しいかどうかを確認しています。私は関数内でこれのためにstringstreamを使うつもりです。私もこのためにoperator=を持っています。文字列をストリングストリームを使用してintに変換しようとしています

私は一緒に、私は何かが欠けていた場合、これらを実行する方法については少し混乱しています。これは私が持っている課題の最後のビットです。これは私の全プログラムのちょっとしたスニペットです。私はこれについて多くのガイドを見つけることができません、そして、私はそれらがすべて私が使用することを許されていないatoiまたはatodに向けると感じます。

このヘッダーでは、=演算子にどのような引数を使用するのかよくわかりません。申し訳ありません

#include <iostream> 
#include <sstream> 
#include <string> 
#include "Integer.h" 
using namespace std; 

Integer &Integer::operator=(const string*) 
{ 
    this->equals(strOne); 
    return *this; 
} 

void Integer::equals(string a) 
{ 
    strOne = a; 
    toString(strOne); 
} 

string Integer::toString() 
{ 
    stringstream ss; 
    ss << intOne; 
    return ss.str(); 
} 



#include <iostream> 
#include <cstdlib> 
#include <conio.h> 
#include <string> 
#include <ostream> 
using namespace std; 
#include "Menu.h" 
#include "Integer.h" 
#include "Double.h" 



int main() 
{ 
    Integer i1; 
    i1.equals("33"); 
    cout << i1; 
} 

その悪い質問は、私はこのタイプの割り当てとあまり慣れていないと私が得ることができる任意の助けを取る場合。ありがとう。

答えて

0

あなたは同じ番号を表す文字列にint型から変換することができますstd::to_strig()を使用することができます。

0

私が正しく理解していれば、が比較のための割り当てに使用されていないので、あなたはオペレータ=を過負荷にしたいと考えています。

正しいオペレータのシグネチャは次のとおりです。

ReturnType operator==(const TypeOne first, const TypeSecond second) [const] // if outside of class 
ReturnType operator==(const TypeSecond second) [const] // if inside class 

あなたが(彼らは異なるタイプの)整数への文字列を比較することはできませんので、あなたは私がするものを持っていないので、あなたは、あなたのcomparisment関数を記述する必要がありますあなたのための1を書き:

// inside your Integer class 
bool operator==(std::string value) const 
{ 
    std::stringstream tmp; 
    tmp << intOne; 
    return tmp.str() == ref; 
} 

bool is_int_equal_string(std::string str, int i) 
{ 
    std::string tmp; 
    tmp << i; 
    return tmp.str() == i; 
} 

なく、少なくとも最後に、あなたは1つの便利な演算子に、それらの両方をマージする必要があります

今、あなたは、他の同じように、この演算子を使用することができます。

Integer foo = 31; 
if (foo == "31") 
    cout << "Is equal" << endl; 
else 
    cout << "Is NOT equal" << endl; 

私はこのことができます願っています。

0

あなたはそれが最善だろうstd::to_stringを使用することを許可されている場合。

そうでなければ、文字列とstd::stringstreamの使用と整数間の平等を処理するための関数を作成することができます。

例:

bool Integer::equal(const string& str) 
{ 
    stringstream ss(str); 
    int str_to_int = 0; 
    ss >> str_to_int; 

    if (intOne == str_to_int) 
     return true; 
    else 
     return false; 
} 

if声明でこれを組み合わせます

int main() 
{ 
    Integer i{100}; 

    if (i.equal("100")) 
     cout << "true" << endl; 
    else 
     cout << "false" << endl; 
} 
関連する問題