1

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!

ESipalis
  • 381
  • 4
  • 17
  • 1
    `bin(` is redundant in your operators; the return value is constructed from the expression after `return`. SO you can write `return addStrings(` etc. – M.M Jul 30 '15 at 21:57

2 Answers2

3

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.

Telokis
  • 3,399
  • 14
  • 36
0

First since your class only has a std::string member you do not need to implement a copy constructor or assignment operator as the default compiler provided ones will work just fine for you.

Secondly all of you operators should take there parameters as a const & so that they can capture temporary objects. This also allows you to chain operators together like foo + bar + cat

NathanOliver
  • 171,901
  • 28
  • 288
  • 402