简体   繁体   中英

how to overload operator + for unsigned char array?

so i need to overload operators (+, -, *, /) to use it with unsigned char arrays; unsigned char array is a number; i wrote this ( only for summ )

#include <iostream>
#include <string>
using namespace std;

class decimal
{
private:
    unsigned char dec[100];
    size_t size;
public:
    decimal(char* get)
    {
        size = strlen(get);
        for (int i = size - 1; i >= 0; i--, get++)
        {
            dec[i] = *get;
            cout << dec[i];
        }       
        cout << endl;
    }
    friend decimal operator + (decimal const &, decimal const &);
};

decimal operator + (decimal const &a, decimal const &b)
{
    int d = atoi((char *)a.dec) + atoi((char *)b.dec);
    string s = to_string(d);
    return decimal(s.c_str);
}

int main()
{
    decimal a("10004");
    decimal b("12");
    decimal c = a + b;
    system("pause");
    return 0;
}

but it gives me errors

error C3867: 'std::basic_string<char,std::char_traits<char>,std::allocator<char>>::c_str': non-standard syntax; use '&' to create a pointer to member
error C2512: 'decimal': no appropriate default constructor available

how can i fix this?

Change the parameter to the constructor to const...

class decimal
{
private:
    unsigned char dec[100];
    size_t size;
public:
    decimal(const char* get)
    {
        size = strlen(get);
        for (int i = size - 1; i >= 0; i--, get++)

Also, change c_str to c_str() .

Better by far, change the constructor parameter from const char* get to const std::string &get) and go from there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM