I've created my own four methods to handle strings as numbers:
std::string addStrings(std::string,std::string);
std::string subtractStrings(std::string,std::string);
std::string multiplyStrings(std::string,std::string);
std::string divideStrings(std::string,std::string);
Then I decided to create big number's class(called bin).I am kinda new to copy constructors and copy assignment operators so,I need your help to fix my code:
class bin{
private:
std::string value;
public:
bin(){}
bin(const char* v1){
value = v1;
}
bin(std::string v1){
value = v1;
}
bin(const bin& other){
value = other.value;
}
bin& operator=(const bin& other){
value = other.value;
return *this;
}
bin& operator=(const char* v1){
value = v1;
return *this;
}
std::string getValue() const{
return value;
}
friend std::ostream& operator<<(std::ostream&,bin&);
};
std::ostream& operator<<(std::ostream& out,bin& v){
out << v.value;
return out;
}
bin operator+(bin& value1,bin& value2){
return bin(addStrings(value1.getValue(),value2.getValue()));
}
bin operator-(bin& value1,bin& value2){
return bin(subtractStrings(value1.getValue(),value2.getValue()));
}
bin operator*(bin& value1,bin& value2){
return bin(multiplyStrings(value1.getValue(),value2.getValue()));
}
bin operator/(bin& value1,bin& value2){
return bin(divideStrings(value1.getValue(),value2.getValue()));
}
Why this works:
bin d = a/c;
std::cout << d << std::endl;
and this doesn't:
std::cout << a/c;
(a and c were declared earlier). Also operator chaining doesn't work,for example:
bin d = a * b + d;
throws:
no match for operator* (operands are bin and bin).
Thank you!
Inside those operators :
operator<<
operator+
operator-
operator*
operator/
You should take const bin&
instead of bin&
. Otherwise your functions won't be able to take a temporary as parameter.
And, when you chain operators, the values returned by each independent operator is a temporary.