如何重载operator + for unsigned char数组?

时间:2018-04-06 18:27:03

标签: c++ arrays

所以我需要重载运算符(+, - ,*,/)以将它与unsigned char数组一起使用; unsigned char数组是一个数字; 我写了这个(仅用于汇总)

#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;
}

但它给了我错误

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

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

将参数更改为构造函数为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++)

另外,将c_str更改为c_str()

更好的是,将构造函数参数从const char* get更改为const std::string &get)并从那里开始。