Error ambiguous overload for operator

I'v read several posts here about this kind of errors, but I wasn't able to solve this one... Has soon I define the operator int and the function f, fails to compile. I tested several things by I ...

I’v read several posts here about this kind of errors, but I wasn’t able to solve this one…
Has soon I define the operator int and the function f, fails to compile.
I tested several things by I wasn’t able to solve the issue….
Thanks

ex1.cpp: In function ‘int main(int, char**)’:
ex1.cpp:35:13: error: ambiguous overload for ‘operator+’ in ‘a + 4’
ex1.cpp:35:13: note: candidates are:
ex1.cpp:35:13: note: operator+(int, int) <built-in>
In file included from ex1.cpp:3:0:
Fraccao.h:41:9: note: Fraccao operator+(const Fraccao&, const Fraccao&)
ex1.cpp:38:13: error: ambiguous overload for ‘operator+’ in ‘4 + a’
ex1.cpp:38:13: note: candidates are:
ex1.cpp:38:13: note: operator+(int, int) <built-in>
In file included from ex1.cpp:3:0:
Fraccao.h:41:9: note: Fraccao operator+(const Fraccao&, const Fraccao&)

The class:

class Fraccao {
    int numerador;
    int denominador;

public:
    Fraccao(int num = 0, int deno = 1) : numerador(num), denominador(deno) {}

    Fraccao & operator+=(const Fraccao &fra);

    Fraccao & operator*=(const Fraccao &fra);

    operator int() const;

    const Fraccao & operator++();
    const Fraccao operator++(int);

    string getAsString() const;
};

Fraccao operator +(const Fraccao &a, const Fraccao &b);
ostream & operator<<(ostream & saida, const Fraccao & fra);

And on my main:

void func(int n) {
    cout << n; // 
}

int main(int argc, char** argv) {
    //...
    d = a + b;
    const Fraccao h(7, 3);
    func(h);

    return 0;
}

What’s the problem?

Due to the way JsonVariant and String implement implicit type conversion, you can construct a String from a JsonVariant, but you cannot assign a JsonVariant to an existing String.

For example, in the following snippet, the first line works but the second produces a compilation error:

String name = doc["name"];  // contruction -> works
name = doc["name"];         // assignment  -> fails

If you try to compile this snippet, you get the following error:

error: ambiguous overload for 'operator=' (operand types are 'String' and ...)
   name = doc["name"];
                    ^
note: candidate: String& String::operator=(const String&)
note: candidate: String& String::operator=(const char*)
note: candidate: String& String::operator=(const __FlashStringHelper*)
note: candidate: String& String::operator=(String&&)
note: candidate: String& String::operator=(StringSumHelper&&)

Indeed, since JsonVariant supports implicit conversion to both const char* and String, the compiler doesn’t know which constructor of String should be called, so it deems the operator as “ambiguous”.

How to solve it?

Solution 1: cast

We need to help the compiler pick the right constructor of String.
One way is to cast the JsonVariant to const char*, like so:

name = (const char*)doc["name"]; 

Note that we cannot cast to String because it’s equivalent to calling the (ambiguous) constructor.

Solution 2: as<T>()

Another way is to use JsonVariant::as<T>(), which explicitly converts the JsonVariant to the specified type.
For example, any of these lines would work:

name = doc["name"].as<const char*>();
name = doc["name"].as<String>();

Solution 3: no String

Lastly, like most String class issues, the best solution is often to replace it with a const char* or a char[].

Indeed, the problem doesn’t exists with const char*:

const char* name = doc["name"];  // contruction -> works
name = doc["name"];              // assignment  -> works as well

Just remember that the variable name points to the value in the JsonDocument, so it’s not a copy.

Instead, if you need to make a copy you can use a char[] like so:

char name[32];
strlcpy(name, doc["name"] | "", 32);

When you use strcpy() or strlcpy(), always provide a default value ("", here) because passing NULL to these functions leads to undefined behavior.

See also

  • ARDUINOJSON_ENABLE_ARDUINO_STRING

2 / 2 / 1

Регистрация: 22.05.2019

Сообщений: 33

1

31.08.2019, 22:04. Показов 6055. Ответов 3


Решал задачку, все делал по презентации. Создал класс рациональных чисел. Нужно перегрузить операторы +, — и т.д. для собственного класса, вроде бы все сделал как в презентации, но вылезает ошибка как в заголовке. Не знаю, что с ней делать…
Прикрепил тот самый фрагмент презентации.
Вот код:

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
#include <iostream>
struct Rational
{
 
    Rational(int numerator = 0, int denominator = 1)
    {
        this->mNumerator = numerator;
        this->mDenominator = denominator;
    }
 
    int gcd(int a, int b)
    {
        int c;
        if (a > b)
        {
            std::swap(a, b);
        }
        while ((b % a) != 0)
        {
            c = b % a;
            b = a;
            a = c;
        }
        return a;
    }
 
    int getNumerator() const
    {
        return mNumerator;
    }
 
    unsigned getDenominator() const
    {
        return mDenominator;
    }
 
    void println()
    {
        std::cout << mNumerator << "/" << mDenominator << std::endl;
    }
 
    void add(Rational rational)
    {
        int c = (mDenominator * rational.mDenominator) / gcd(mDenominator, rational.mDenominator);
        mNumerator = mNumerator * (c / mDenominator);
        rational.mNumerator = rational.mNumerator * (c / rational.mDenominator);
        mNumerator = mNumerator + rational.mNumerator;
        int f = gcd(mNumerator, c);
        mNumerator = mNumerator / f;
        mDenominator = c / f;
    }
 
    void sub(Rational rational)
    {
        int c = (mDenominator * rational.mDenominator) / gcd(mDenominator, rational.mDenominator);
        mNumerator = mNumerator * (c / mDenominator);
        rational.mNumerator = rational.mNumerator * (c / rational.mDenominator);
        mNumerator = mNumerator - rational.mNumerator;
        int f = gcd(mNumerator, c);
        mNumerator = mNumerator / f;
        mDenominator = c / f;
    }
 
    void mul(Rational rational)
    {
        mNumerator = mNumerator * rational.mNumerator;
        mDenominator = mDenominator * rational.mDenominator;
        int c = gcd(mNumerator, mDenominator);
        mNumerator = mNumerator / c;
        mDenominator = mDenominator / c;
    }
 
    void div(Rational rational)
    {
        int c = rational.mDenominator;
        rational.mDenominator = rational.mNumerator;
        rational.mNumerator = c;
        mNumerator = mNumerator * rational.mNumerator;
        mDenominator = mDenominator * rational.mDenominator;
        c = gcd(mNumerator, mDenominator);
        mNumerator = mNumerator / c;
        mDenominator = mDenominator / c;
    }
 
    void neg()
    {
        mNumerator = (-1) * mNumerator;
    }
 
 
    double toDouble() const
    {
        return double(mNumerator) / mDenominator;
    }
 
    operator double() const
    {
        return toDouble();
    }
 
    Rational &operator~()
    {
        this->neg();
        return *this;
    }
 
    Rational &operator=(Rational rational)
    {
        this->mNumerator = rational.mNumerator;
        this->mDenominator = rational.mDenominator;
        return *this;
    }
 
    friend std::istream &operator>>(std::istream &in, Rational &rational)
    {
        in >> rational.mNumerator >> rational.mDenominator;
        return in;
    }
 
    friend std::ostream &operator<<(std::ostream &out, Rational &rational)
    {
        out << rational.mNumerator << " \ " << rational.mDenominator;
        return out;
    }
 
    Rational &operator+=(const Rational &rational)
    {
        this->add(rational);
        return *this;
    }
 
 
    Rational &operator+=(const int d)
    {
        this->add(Rational(d));
        return *this;
    }
 
    Rational &operator-=(const Rational &rational)
    {
        this->sub(rational);
        return *this;
    }
 
    Rational &operator-=(const int d)
    {
        this->sub(Rational(d));
        return *this;
    }
 
    Rational &operator*=(const Rational &rational)
    {
        this->mul(rational);
        return *this;
    }
 
    Rational &operator*=(const int d)
    {
        this->mul(Rational(d));
        return *this;
    }
 
    Rational &operator/=(const Rational &rational)
    {
        this->div(rational);
        return *this;
    }
 
    Rational &operator/=(const int d)
    {
        this->div(Rational(d));
        return *this;
    }
 
    Rational operator-() const
    {
        Rational rational(this->mNumerator, this->mDenominator);
        rational.neg();
        return rational;
    }
 
    Rational operator+() const
    {
        Rational rational(this->mNumerator, this->mDenominator);
        return rational;
    }
 
private:
    int mNumerator;
    int mDenominator;
 
};
 
Rational operator+(Rational r1, Rational const &r2)
{
    return r1 += r2;
}
 
Rational operator-(Rational r1, Rational const &r2)
{
    return r1 -= r2;
}
 
Rational operator*(Rational r1, Rational const &r2)
{
    return r1 *= r2;
}
 
Rational operator/(Rational r1, Rational const &r2)
{
    return r1 /= r2;
}
 
bool operator==(Rational const &r1, Rational const &r2)
{
    if (r1.getNumerator() * r2.getDenominator() == r2.getNumerator() * r1.getDenominator())
    {
        return true;
    } else
    {
        return false;
    }
}
 
bool operator!=(Rational const &r1, Rational const &r2)
{
    return !(r1 == r2);
}
 
bool operator<(Rational const &r1, Rational const &r2)
{
    int check = r1.getNumerator() * r2.getDenominator() - r2.getNumerator() * r1.getDenominator();
    if (check < 0)
    {
        return true;
    } else
    {
        return false;
    }
}
 
bool operator>(Rational const &r1, Rational const &r2)
{
    return !(r1 < r2) && !(r1 == r2);
}
 
bool operator<=(Rational const &r1, Rational const &r2)
{
    return (r1 < r2) || (r1 == r2);
}
 
bool operator>=(Rational const &r1, Rational const &r2)
{
    return (r1 > r2) || (r1 == r2);
}

теперь main:

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include "Rational.cpp"
 
 
int main() {
    Rational r (5, 7);
    std::cout << r;
    Rational r2 (6, 8);
    r += r2;
    r.println();
    Rational r1;
    r1 = 2;
    r1 = 2+2;
    r1 += r + r;
    r1 += 2 + r;  //здесь ругается
    r1 += r + 2;   // и здесь
    r1.println();
    r1->println();
    if (r > r2) {
        std::cout << (double)r1;
    }
    return 0;

Подскажите пожалуйста в чем проблема…

Миниатюры

Ambiguous overload for 'operator+' (operand types are 'int' and 'Rational')
 

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



I tried to compile litecoin. I got the following error.

chainparams.cpp: In constructor ‘CMainParams::CMainParams()’:
chainparams.cpp:166:52: error: ambiguous overload for ‘operator=’ (operand types are ‘std::vector<unsigned char>’ and ‘boost::assign_detail::generic_list<int>’)
         base58Prefixes[PUBKEY_ADDRESS] = list_of(48);
                                                    ^
In file included from /usr/include/c++/6.1.1/vector:69:0,
                 from chainparamsbase.h:9,
                 from chainparams.h:9,
                 from chainparams.cpp:6:
/usr/include/c++/6.1.1/bits/vector.tcc:167:5: note: candidate: std::vector<_Tp, _Alloc>& std::vector<_Tp, _Alloc>::operator=(const std::vector<_Tp, _Alloc>&) [with _Tp = unsigned char; _Alloc = std::allocator<unsigned char>]
     vector<_Tp, _Alloc>::
     ^~~~~~~~~~~~~~~~~~~
In file included from /usr/include/c++/6.1.1/vector:64:0,
                 from chainparamsbase.h:9,
                 from chainparams.h:9,
                 from chainparams.cpp:6:
/usr/include/c++/6.1.1/bits/stl_vector.h:450:7: note: candidate: std::vector<_Tp, _Alloc>& std::vector<_Tp, _Alloc>::operator=(std::vector<_Tp, _Alloc>&&) [with _Tp = unsigned char; _Alloc = std::allocator<unsigned char>]
       operator=(vector&& __x) noexcept(_Alloc_traits::_S_nothrow_move())
       ^~~~~~~~
/usr/include/c++/6.1.1/bits/stl_vector.h:471:7: note: candidate: std::vector<_Tp, _Alloc>& std::vector<_Tp, _Alloc>::operator=(std::initializer_list<_Tp>) [with _Tp = unsigned char; _Alloc = std::allocator<unsigned char>]
       operator=(initializer_list<value_type> __l)
       ^~~~~~~~
chainparams.cpp:167:51: error: ambiguous overload for ‘operator=’ (operand types are ‘std::vector<unsigned char>’ and ‘boost::assign_detail::generic_list<int>’)
         base58Prefixes[SCRIPT_ADDRESS] = list_of(5);
                                                   ^
In file included from /usr/include/c++/6.1.1/vector:69:0,
                 from chainparamsbase.h:9,
                 from chainparams.h:9,
                 from chainparams.cpp:6:
/usr/include/c++/6.1.1/bits/vector.tcc:167:5: note: candidate: std::vector<_Tp, _Alloc>& std::vector<_Tp, _Alloc>::operator=(const std::vector<_Tp, _Alloc>&) [with _Tp = unsigned char; _Alloc = std::allocator<unsigned char>]
     vector<_Tp, _Alloc>::
     ^~~~~~~~~~~~~~~~~~~
In file included from /usr/include/c++/6.1.1/vector:64:0,
                 from chainparamsbase.h:9,
                 from chainparams.h:9,
                 from chainparams.cpp:6:
/usr/include/c++/6.1.1/bits/stl_vector.h:450:7: note: candidate: std::vector<_Tp, _Alloc>& std::vector<_Tp, _Alloc>::operator=(std::vector<_Tp, _Alloc>&&) [with _Tp = unsigned char; _Alloc = std::allocator<unsigned char>]
       operator=(vector&& __x) noexcept(_Alloc_traits::_S_nothrow_move())
       ^~~~~~~~
/usr/include/c++/6.1.1/bits/stl_vector.h:471:7: note: candidate: std::vector<_Tp, _Alloc>& std::vector<_Tp, _Alloc>::operator=(std::initializer_list<_Tp>) [with _Tp = unsigned char; _Alloc = std::allocator<unsigned char>]
       operator=(initializer_list<value_type> __l)
       ^~~~~~~~
chainparams.cpp:168:53: error: ambiguous overload for ‘operator=’ (operand types are ‘std::vector<unsigned char>’ and ‘boost::assign_detail::generic_list<int>’)
         base58Prefixes[SECRET_KEY] =     list_of(176);
                                                     ^
In file included from /usr/include/c++/6.1.1/vector:69:0,
                 from chainparamsbase.h:9,
                 from chainparams.h:9,
                 from chainparams.cpp:6:
/usr/include/c++/6.1.1/bits/vector.tcc:167:5: note: candidate: std::vector<_Tp, _Alloc>& std::vector<_Tp, _Alloc>::operator=(const std::vector<_Tp, _Alloc>&) [with _Tp = unsigned char; _Alloc = std::allocator<unsigned char>]
     vector<_Tp, _Alloc>::
     ^~~~~~~~~~~~~~~~~~~
In file included from /usr/include/c++/6.1.1/vector:64:0,
                 from chainparamsbase.h:9,
                 from chainparams.h:9,
                 from chainparams.cpp:6:
/usr/include/c++/6.1.1/bits/stl_vector.h:450:7: note: candidate: std::vector<_Tp, _Alloc>& std::vector<_Tp, _Alloc>::operator=(std::vector<_Tp, _Alloc>&&) [with _Tp = unsigned char; _Alloc = std::allocator<unsigned char>]
       operator=(vector&& __x) noexcept(_Alloc_traits::_S_nothrow_move())
       ^~~~~~~~
/usr/include/c++/6.1.1/bits/stl_vector.h:471:7: note: candidate: std::vector<_Tp, _Alloc>& std::vector<_Tp, _Alloc>::operator=(std::initializer_list<_Tp>) [with _Tp = unsigned char; _Alloc = std::allocator<unsigned char>]
       operator=(initializer_list<value_type> __l)
       ^~~~~~~~
chainparams.cpp:169:72: error: ambiguous overload for ‘operator=’ (operand types are ‘std::vector<unsigned char>’ and ‘boost::assign_detail::generic_list<int>’)
         base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x88)(0xB2)(0x1E);
                                                                        ^
In file included from /usr/include/c++/6.1.1/vector:69:0,
                 from chainparamsbase.h:9,
                 from chainparams.h:9,
                 from chainparams.cpp:6:
/usr/include/c++/6.1.1/bits/vector.tcc:167:5: note: candidate: std::vector<_Tp, _Alloc>& std::vector<_Tp, _Alloc>::operator=(const std::vector<_Tp, _Alloc>&) [with _Tp = unsigned char; _Alloc = std::allocator<unsigned char>]
     vector<_Tp, _Alloc>::
     ^~~~~~~~~~~~~~~~~~~
In file included from /usr/include/c++/6.1.1/vector:64:0,
                 from chainparamsbase.h:9,
                 from chainparams.h:9,
                 from chainparams.cpp:6:
/usr/include/c++/6.1.1/bits/stl_vector.h:450:7: note: candidate: std::vector<_Tp, _Alloc>& std::vector<_Tp, _Alloc>::operator=(std::vector<_Tp, _Alloc>&&) [with _Tp = unsigned char; _Alloc = std::allocator<unsigned char>]
       operator=(vector&& __x) noexcept(_Alloc_traits::_S_nothrow_move())
       ^~~~~~~~
/usr/include/c++/6.1.1/bits/stl_vector.h:471:7: note: candidate: std::vector<_Tp, _Alloc>& std::vector<_Tp, _Alloc>::operator=(std::initializer_list<_Tp>) [with _Tp = unsigned char; _Alloc = std::allocator<unsigned char>]
       operator=(initializer_list<value_type> __l)
       ^~~~~~~~
chainparams.cpp:170:72: error: ambiguous overload for ‘operator=’ (operand types are ‘std::vector<unsigned char>’ and ‘boost::assign_detail::generic_list<int>’)
         base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x88)(0xAD)(0xE4);
                                                                        ^
In file included from /usr/include/c++/6.1.1/vector:69:0,
                 from chainparamsbase.h:9,
                 from chainparams.h:9,
                 from chainparams.cpp:6:
/usr/include/c++/6.1.1/bits/vector.tcc:167:5: note: candidate: std::vector<_Tp, _Alloc>& std::vector<_Tp, _Alloc>::operator=(const std::vector<_Tp, _Alloc>&) [with _Tp = unsigned char; _Alloc = std::allocator<unsigned char>]
     vector<_Tp, _Alloc>::
     ^~~~~~~~~~~~~~~~~~~
In file included from /usr/include/c++/6.1.1/vector:64:0,
                 from chainparamsbase.h:9,
                 from chainparams.h:9,
                 from chainparams.cpp:6:
/usr/include/c++/6.1.1/bits/stl_vector.h:450:7: note: candidate: std::vector<_Tp, _Alloc>& std::vector<_Tp, _Alloc>::operator=(std::vector<_Tp, _Alloc>&&) [with _Tp = unsigned char; _Alloc = std::allocator<unsigned char>]
       operator=(vector&& __x) noexcept(_Alloc_traits::_S_nothrow_move())
       ^~~~~~~~
/usr/include/c++/6.1.1/bits/stl_vector.h:471:7: note: candidate: std::vector<_Tp, _Alloc>& std::vector<_Tp, _Alloc>::operator=(std::initializer_list<_Tp>) [with _Tp = unsigned char; _Alloc = std::allocator<unsigned char>]
       operator=(initializer_list<value_type> __l)
       ^~~~~~~~
chainparams.cpp: In constructor ‘CTestNetParams::CTestNetParams()’:
chainparams.cpp:228:53: error: ambiguous overload for ‘operator=’ (operand types are ‘std::vector<unsigned char>’ and ‘boost::assign_detail::generic_list<int>’)
         base58Prefixes[PUBKEY_ADDRESS] = list_of(111);
                                                     ^
In file included from /usr/include/c++/6.1.1/vector:69:0,
                 from chainparamsbase.h:9,
                 from chainparams.h:9,
                 from chainparams.cpp:6:
/usr/include/c++/6.1.1/bits/vector.tcc:167:5: note: candidate: std::vector<_Tp, _Alloc>& std::vector<_Tp, _Alloc>::operator=(const std::vector<_Tp, _Alloc>&) [with _Tp = unsigned char; _Alloc = std::allocator<unsigned char>]
     vector<_Tp, _Alloc>::
     ^~~~~~~~~~~~~~~~~~~
In file included from /usr/include/c++/6.1.1/vector:64:0,
                 from chainparamsbase.h:9,
                 from chainparams.h:9,
                 from chainparams.cpp:6:
/usr/include/c++/6.1.1/bits/stl_vector.h:450:7: note: candidate: std::vector<_Tp, _Alloc>& std::vector<_Tp, _Alloc>::operator=(std::vector<_Tp, _Alloc>&&) [with _Tp = unsigned char; _Alloc = std::allocator<unsigned char>]
       operator=(vector&& __x) noexcept(_Alloc_traits::_S_nothrow_move())
       ^~~~~~~~
/usr/include/c++/6.1.1/bits/stl_vector.h:471:7: note: candidate: std::vector<_Tp, _Alloc>& std::vector<_Tp, _Alloc>::operator=(std::initializer_list<_Tp>) [with _Tp = unsigned char; _Alloc = std::allocator<unsigned char>]
       operator=(initializer_list<value_type> __l)
       ^~~~~~~~
chainparams.cpp:229:53: error: ambiguous overload for ‘operator=’ (operand types are ‘std::vector<unsigned char>’ and ‘boost::assign_detail::generic_list<int>’)
         base58Prefixes[SCRIPT_ADDRESS] = list_of(196);
                                                     ^
In file included from /usr/include/c++/6.1.1/vector:69:0,
                 from chainparamsbase.h:9,
                 from chainparams.h:9,
                 from chainparams.cpp:6:
/usr/include/c++/6.1.1/bits/vector.tcc:167:5: note: candidate: std::vector<_Tp, _Alloc>& std::vector<_Tp, _Alloc>::operator=(const std::vector<_Tp, _Alloc>&) [with _Tp = unsigned char; _Alloc = std::allocator<unsigned char>]
     vector<_Tp, _Alloc>::
     ^~~~~~~~~~~~~~~~~~~
In file included from /usr/include/c++/6.1.1/vector:64:0,
                 from chainparamsbase.h:9,
                 from chainparams.h:9,
                 from chainparams.cpp:6:
/usr/include/c++/6.1.1/bits/stl_vector.h:450:7: note: candidate: std::vector<_Tp, _Alloc>& std::vector<_Tp, _Alloc>::operator=(std::vector<_Tp, _Alloc>&&) [with _Tp = unsigned char; _Alloc = std::allocator<unsigned char>]
       operator=(vector&& __x) noexcept(_Alloc_traits::_S_nothrow_move())
       ^~~~~~~~
/usr/include/c++/6.1.1/bits/stl_vector.h:471:7: note: candidate: std::vector<_Tp, _Alloc>& std::vector<_Tp, _Alloc>::operator=(std::initializer_list<_Tp>) [with _Tp = unsigned char; _Alloc = std::allocator<unsigned char>]
       operator=(initializer_list<value_type> __l)
       ^~~~~~~~
chainparams.cpp:230:53: error: ambiguous overload for ‘operator=’ (operand types are ‘std::vector<unsigned char>’ and ‘boost::assign_detail::generic_list<int>’)
         base58Prefixes[SECRET_KEY]     = list_of(239);
                                                     ^
In file included from /usr/include/c++/6.1.1/vector:69:0,
                 from chainparamsbase.h:9,
                 from chainparams.h:9,
                 from chainparams.cpp:6:
/usr/include/c++/6.1.1/bits/vector.tcc:167:5: note: candidate: std::vector<_Tp, _Alloc>& std::vector<_Tp, _Alloc>::operator=(const std::vector<_Tp, _Alloc>&) [with _Tp = unsigned char; _Alloc = std::allocator<unsigned char>]
     vector<_Tp, _Alloc>::
     ^~~~~~~~~~~~~~~~~~~
In file included from /usr/include/c++/6.1.1/vector:64:0,
                 from chainparamsbase.h:9,
                 from chainparams.h:9,
                 from chainparams.cpp:6:
/usr/include/c++/6.1.1/bits/stl_vector.h:450:7: note: candidate: std::vector<_Tp, _Alloc>& std::vector<_Tp, _Alloc>::operator=(std::vector<_Tp, _Alloc>&&) [with _Tp = unsigned char; _Alloc = std::allocator<unsigned char>]
       operator=(vector&& __x) noexcept(_Alloc_traits::_S_nothrow_move())
       ^~~~~~~~
/usr/include/c++/6.1.1/bits/stl_vector.h:471:7: note: candidate: std::vector<_Tp, _Alloc>& std::vector<_Tp, _Alloc>::operator=(std::initializer_list<_Tp>) [with _Tp = unsigned char; _Alloc = std::allocator<unsigned char>]
       operator=(initializer_list<value_type> __l)
       ^~~~~~~~
chainparams.cpp:231:72: error: ambiguous overload for ‘operator=’ (operand types are ‘std::vector<unsigned char>’ and ‘boost::assign_detail::generic_list<int>’)
         base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x35)(0x87)(0xCF);
                                                                        ^
In file included from /usr/include/c++/6.1.1/vector:69:0,
                 from chainparamsbase.h:9,
                 from chainparams.h:9,
                 from chainparams.cpp:6:
/usr/include/c++/6.1.1/bits/vector.tcc:167:5: note: candidate: std::vector<_Tp, _Alloc>& std::vector<_Tp, _Alloc>::operator=(const std::vector<_Tp, _Alloc>&) [with _Tp = unsigned char; _Alloc = std::allocator<unsigned char>]
     vector<_Tp, _Alloc>::
     ^~~~~~~~~~~~~~~~~~~
In file included from /usr/include/c++/6.1.1/vector:64:0,
                 from chainparamsbase.h:9,
                 from chainparams.h:9,
                 from chainparams.cpp:6:
/usr/include/c++/6.1.1/bits/stl_vector.h:450:7: note: candidate: std::vector<_Tp, _Alloc>& std::vector<_Tp, _Alloc>::operator=(std::vector<_Tp, _Alloc>&&) [with _Tp = unsigned char; _Alloc = std::allocator<unsigned char>]
       operator=(vector&& __x) noexcept(_Alloc_traits::_S_nothrow_move())
       ^~~~~~~~
/usr/include/c++/6.1.1/bits/stl_vector.h:471:7: note: candidate: std::vector<_Tp, _Alloc>& std::vector<_Tp, _Alloc>::operator=(std::initializer_list<_Tp>) [with _Tp = unsigned char; _Alloc = std::allocator<unsigned char>]
       operator=(initializer_list<value_type> __l)
       ^~~~~~~~
chainparams.cpp:232:72: error: ambiguous overload for ‘operator=’ (operand types are ‘std::vector<unsigned char>’ and ‘boost::assign_detail::generic_list<int>’)
         base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x35)(0x83)(0x94);
                                                                        ^
In file included from /usr/include/c++/6.1.1/vector:69:0,
                 from chainparamsbase.h:9,
                 from chainparams.h:9,
                 from chainparams.cpp:6:
/usr/include/c++/6.1.1/bits/vector.tcc:167:5: note: candidate: std::vector<_Tp, _Alloc>& std::vector<_Tp, _Alloc>::operator=(const std::vector<_Tp, _Alloc>&) [with _Tp = unsigned char; _Alloc = std::allocator<unsigned char>]
     vector<_Tp, _Alloc>::
     ^~~~~~~~~~~~~~~~~~~
In file included from /usr/include/c++/6.1.1/vector:64:0,
                 from chainparamsbase.h:9,
                 from chainparams.h:9,
                 from chainparams.cpp:6:
/usr/include/c++/6.1.1/bits/stl_vector.h:450:7: note: candidate: std::vector<_Tp, _Alloc>& std::vector<_Tp, _Alloc>::operator=(std::vector<_Tp, _Alloc>&&) [with _Tp = unsigned char; _Alloc = std::allocator<unsigned char>]
       operator=(vector&& __x) noexcept(_Alloc_traits::_S_nothrow_move())
       ^~~~~~~~
/usr/include/c++/6.1.1/bits/stl_vector.h:471:7: note: candidate: std::vector<_Tp, _Alloc>& std::vector<_Tp, _Alloc>::operator=(std::initializer_list<_Tp>) [with _Tp = unsigned char; _Alloc = std::allocator<unsigned char>]
       operator=(initializer_list<value_type> __l)
       ^~~~~~~~

The below section deals about overload resolution as it helps in the fundamentals of overloading and overriding.
Predict the output:

#include <iostream>

using namespace std;

class Gfg {

public:

    void printHello()

    {

        cout << "hello gfg-class specific" << endl;

    }

};

void printHello()

{

    cout << "hello gfg-global" << endl;

}

int main()

{

    Gfg a;

    a.printHello();

    printHello();

}

Output:
hello gfg-class specific
hello gfg-global

How does the compiler differentiates the class-specific function and a global function?
To map the function call with the corresponding function definition, the compiler performs the process of name-lookup. This process yields some set of functions that have the same name and they are called candidate functions. If there is more than one candidate function, the compiler performs the argument-dependent lookup process. If this process also yields more than one candidate function, then the process of overload resolution is carried out to select the function that has to be called.
If any of the candidate functions is a member function of the corresponding class (static or non-static), it is prepended with an implicit object parameter which represents the object for which they are called and appears before the first of the actual parameters.

Predict the output:

#include <iostream>

using namespace std;

class Gfg {

public:

    Gfg operator+(Gfg& a)

    {

        cout << "class specific + operator" << endl;

        return Gfg();

    }

};

Gfg operator+(Gfg& a, Gfg& b)

{

    cout << "global + operator called" << endl;

    return Gfg();

}

int main()

{

    Gfg a, b;

    Gfg c = a + b;

}

Output: Compilation error
plusOverride.cpp: In function ‘int main()’:
plusOverride.cpp:19:9: error: ambiguous overload for ‘operator+’ 
(operand types are ‘Gfg’ and ‘Gfg’)
  Gfg c=a+b;
         ^
plusOverride.cpp:19:9: note: candidates are:
plusOverride.cpp:6:9: note: Gfg Gfg::operator+(Gfg&)
     Gfg operator+(Gfg& a){
         ^
plusOverride.cpp:12:5: note: Gfg operator+(Gfg&, Gfg&)
 Gfg operator+(Gfg& a, Gfg& b){
     ^

This is how overload resolution works with operator overloading:
The candidate functions for both the unary and binary operators are selected from different scopes. They are
1) member candidates: The operator overloaded functions defined in the class.
2) non-member candidates: The operator overloaded functions that are global.
3) built-in candidates: The built-in functions that perform the specified operation.
Hence, for the above program during the compilation, the number of candidate functions is more than one and all these candidate functions have the same precedence and hence the ambiguous overload error arises.
Predict the output:

#include <iostream>

#include <stdio.h>

#include <stdlib.h>

using namespace std;

class Gfg {

public:

    int a;

    void* operator new(size_t sz)

    {

        cout << "class-specific new for size " << sz << 'n';

        return malloc(sz);

    }

    void* operator new[](size_t sz)

    {

        cout << "class-specific new[] for size " << sz << 'n';

        return malloc(sz);

    }

};

void* operator new[](size_t sz)

{

    cout << "global new[] for size" << sz << 'n';

    return malloc(sz);

}

void* operator new(size_t sz)

{

    cout << "global new for size" << sz << 'n';

    return malloc(sz);

}

int main()

{

    Gfg* p1 = new Gfg;

    delete p1;

    Gfg* p2 = new Gfg[10];

    delete[] p2;

}

Output: 
class-specific new for size 4
class specific new[] for size 40

The program worked for the following reasons:
The C++ standards state that “If a class has a class-specific allocation function, it is the function that will be called, not the global allocation function. This is intentional: the class member is expected to know best how to handle that class”. It means, when the new expression looks for the corresponding allocation function, it begins at class scope before examining the global scope, and if the class-specific new is provided, it is invoked. Else it checks for the global scope and invokes it. If the global scope new function is not present, it will invoke the built-in new function. Henceforth, the candidate functions do not have the same precedence in the above example and hence it compiles without any error.

Can the programmer invoke the global new operator even if the class-specific new operator is defined?
Yes. C++ provides the scope-resolution operator for that purpose. If the new operator is preceded with the scope resolution(::) operator, the compiler searches for the operator new in the global scope.

What happens if the new operator is not defined in the global scope and you are calling the new operator using the :: unary operator?
The compiler will invoke the built-in new function. The following example demonstrates how it works. It does contain the class-specific operator new but the global operator new. Henceforth, while invoking ::new, the compiler invokes the standard library new function.

#include <iostream>

#include <stdio.h>

#include <stdlib.h>

using namespace std;

class Gfg {

public:

    int a;

    void* operator new(size_t sz)

    {

        cout << "class-specific new for size " << sz << 'n';

        return malloc(sz);

    }

    void* operator new[](size_t sz)

    {

        cout << "class-specific new[] for size " << sz << 'n';

        return malloc(sz);

    }

};

void* operator new[](size_t sz)

{

    cout << "global new[] for size " << sz << 'n';

    return malloc(sz);

}

int main()

{

    Gfg* p1 = ::new Gfg;

    cout << "Allocated sie of p1: " << sizeof(*p1) << endl;

    delete p1;

    Gfg* p2 = ::new Gfg[10];

    delete[] p2;

}

Output:
Allocated sie of p1: 4
global new[] for size 40

Why C++ provides this extensibility for new function?

  1. Performance: The built-in memory allocator function is a general purpose function and it fits for predefined data-types. For user-defined data-types that have very specific data to be allocated, and by customizing the way they’re allocated you can speed up memory management considerably.
  2. Debugging & statistics: Possessing the control over the way the memory is being spent provides great flexibility for debugging, statistics and performance analysis.

These are some of the various reasons to make the programming easier while solving complex problems.

Unfortunately that didn’t resolve the problem. The compiler can’t choose which operator=() to use, and it’s looks like because the operator T() is being chosen over the operator std::string()?!?

(If I remove the operator T() and replace it with just operator std::string() it compiles fine (for the string = csv::token() )

src/main.cpp:53: error: ambiguous overload for ‘operator=’ in ‘foo = csv::token(((csv::parse&)(& p)))’
/usr/include/c++/4.4/bits/basic_string.h:505: note: candidates are: std::basic_string<_CharT, _Traits, _Alloc>& std::basic_string<_CharT, _Traits, _Alloc>::operator=(const std::basic_string<_CharT, _Traits, _Alloc>&) [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>]
/usr/include/c++/4.4/bits/basic_string.h:513: note:                 std::basic_string<_CharT, _Traits, _Alloc>& std::basic_string<_CharT, _Traits, _Alloc>::operator=(const _CharT*) [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>]
/usr/include/c++/4.4/bits/basic_string.h:524: note:                 std::basic_string<_CharT, _Traits, _Alloc>& std::basic_string<_CharT, _Traits, _Alloc>::operator=(_CharT) [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>]
/usr/include/c++/4.4/bits/basic_string.h:536: note:                 std::basic_string<_CharT, _Traits, _Alloc>& std::basic_string<_CharT, _Traits, _Alloc>::operator=(std::initializer_list<_CharT>) [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>]

I like to expand the use of my application and to this goal I like to
declare
QStringList expressionList ;
as class variable member

and define it in code
expressionList = {«([0-F]{2}[:]){5}[0-F]{2}»,»Agent registered»,»Controller»,»Pairable: yes»};

I am receiving this error and I do not understand why and of course have no idea how to fix it.

If I define it this way , in body of the code , it works just fine as a «local variable».
QStringList expressionList = {«([0-F]{2}[:]){5}[0-F]{2}»,»Agent registered»,»Controller»,»Pairable: yes»};

Do I have to build the list from individual QString ?

/mnt/MDI_RAID_5/MDI_WORK_COPY_FOLDER/MDI_BT_Aug1_BASE/MDI_BT/MDI_BT/C_BLUETOOTHCTL/C_bluetoothctl/mainwindow_bluetoothctl.cpp:5721: error: ambiguous overload for ‘operator=’ (operand types are ‘QStringList’ and ‘<brace-enclosed initializer list>’)
mainwindow_bluetoothctl.cpp: In member function ‘void MainWindow_Bluetoothctl::on_lineEdit_8_returnPressed()’:
mainwindow_bluetoothctl.cpp:5721:115: error: ambiguous overload for ‘operator=’ (operand types are ‘QStringList’ and ‘<brace-enclosed initializer list>’)
5721 | expressionList = {«([0-F]{2}[:]){5}[0-F]{2}»,»Agent registered»,»Controller»,»Pairable: yes»};
| ^

  1. 05-11-2011


    #1

    Cobs is offline


    Registered User


    ambiguous overload for operators…

    i have a little problem and i cant figure it out.

    here is a piece of code:

    Code:

    ...
     
     struct razlomak {
            
            int brojnik, nazivnik;       
            
            razlomak( int br = 0, int naz = 1 ) { brojnik = br; nazivnik = naz; skratiMe(); }
            
         ...
            
            razlomak operator+( const razlomak& b ){
                     
                     razlomak vrati( brojnik*b.nazivnik + nazivnik*b.brojnik, nazivnik*b.nazivnik );
                              
                     return vrati;         
                              
            }
            
            razlomak operator-( const razlomak& b ){
                     
                    razlomak vrati( brojnik*b.nazivnik - nazivnik*b.brojnik, nazivnik*b.nazivnik ); 
                              
                    return vrati;          
                              
            }
            
            razlomak operator-(){
                 
                 razlomak vrati( -brojnik, nazivnik );
                 
                 return vrati;
                        
            }
            
            
            friend ostream& operator<<( ostream& , const razlomak& );
            friend razlomak operator+( const razlomak&, const razlomak& );
            friend razlomak operator-( int, const razlomak& );
            
            bool operator==( const razlomak& b ){
                  if( brojnik == b.brojnik && nazivnik == b.nazivnik ) return true;
                  return false;
            }
            
            bool operator<=( const razlomak& b ){
                 if( brojnik*b.nazivnik <= nazivnik*b.brojnik ) return true;
                 return false;      
            }
            
            bool operator<( const razlomak& b ){
                 if( brojnik*b.nazivnik < nazivnik*b.brojnik ) return true;
                 return false;      
            }
            
             bool operator>=( const razlomak& b ){
                 if( brojnik*b.nazivnik >= nazivnik*b.brojnik ) return true;
                 return false;      
            }
            
            bool operator>( const razlomak& b ){
                 if( brojnik*b.nazivnik > nazivnik*b.brojnik ) return true;
                 return false;      
            }
            
            bool operator!=( const razlomak& b ){
                 if( brojnik*b.nazivnik != nazivnik*b.brojnik ) return true;
                 return false;      
            }
            
            operator bool(){
                 if( brojnik != 0 ) return true;
                 return false;     
            }
            
            bool operator!(){ 
                 if( brojnik == 0 ) return true;
                 return false;     
            }
            
            friend bool operator==( int, const razlomak& );
            friend bool operator<=( int, const razlomak& );
            friend bool operator<( int, const razlomak& );
            friend bool operator>=( int, const razlomak& );
            friend bool operator>( int, const razlomak& );
            friend bool operator!=( int, const razlomak& );
            
            
     };
     
     ostream& operator<<( ostream& r, const razlomak& x ){
              r << x.brojnik << " / " << x.nazivnik;
              return r;          
     }
     
     razlomak operator-( int a, const razlomak& b ){
              
              return razlomak( a*b.nazivnik - b.brojnik, b.nazivnik );
                       
     }
     
     razlomak operator+( int, const razlomak& b ){
               return razlomak( a*b.nazivnik + b.brojnik, b.nazivnik );
              
     }
     
     bool operator==( int a, const razlomak& b ){
                 if( a == b.brojnik && b.nazivnik == 1 ) return true;
                 return false;      
     }
     
     bool operator<=( int a, const razlomak& b ){
                 if( a*b.nazivnik <= b.brojnik ) return true;
                 return false;      
     }
     
     bool operator<( int a, const razlomak& b ){
                 if( a*b.nazivnik < b.brojnik ) return true;
                 return false;      
     }
     
     bool operator>=( int a, const razlomak& b ){
                 if( a*b.nazivnik >= b.brojnik ) return true;
                 return false;      
     }
     
     bool operator>( int a, const razlomak& b ){
                 if( a*b.nazivnik > b.brojnik ) return true;
                 return false;      
     }
     
     bool operator!=( int a, const razlomak& b ){
                 if( a != b.brojnik || 1 != b.nazivnik ) return true;
                 return false;      
     }
     
     int main(){ 
         
      razlomak A( 3, 9 );
      razlomak B( 4, 16 );
      
      cout << A+B << endl; 
      cout << A+1 << endl; 
      cout << 1+A << endl;
      cout << 1-A << endl; 
     
      cin.get();
      return 0;    
         
     }

    compiler is throwing me an error for ambiguous overload of operator + in

    line:

    Code:

    cout << A+1 << endl;

    but i dont know where is the problem?
    compiler says that candidates are:
    operator+( int, int ) ??? why ?
    operator+( const razlomak& ) -> this should be ok ( after implicit conversion of 1 )
    operator+( int, const razlomak& ) ???

    and the strange thing in problem is that if i dont have all this operators of comparisons everthing works just fine ( so the problem is not in the code? ).


  2. 05-11-2011


    #2

    tabstop is offline


    and the Hat of Guessing

    tabstop's Avatar


    + is not automatically commutative — defining int + razlomak gives no information whatsoever on how to do razlomak + int. The two outside versions suggest that the compiler is finding a conversion from razlomak to int (did you define an operator int() for the class?).


  3. 05-11-2011


    #3

    Cobs is offline


    Registered User


    Quote Originally Posted by tabstop
    View Post

    + is not automatically commutative — defining int + razlomak gives no information whatsoever on how to do razlomak + int. The two outside versions suggest that the compiler is finding a conversion from razlomak to int (did you define an operator int() for the class?).

    razlomak + int should work because int should implicitly convert into razlomak. And that works fine without all this operators of comparison… ( just include iostream, use std, and erase using function skratiMe() in constructor, and comment all operators of comparison ), but with them it’s not working…

    razlomak + int.
    int implicitly converts into razlomak ( constructor is razlomak( int=0,int=1 ) ), and than it should works with razlomak + razlomak.
    Didnt do cast to int, so that’s not the reason for problem int+int

    Last edited by Cobs; 05-11-2011 at 05:41 PM.


  4. 05-11-2011


    #4

    whiteflags is offline


    Lurking

    whiteflags's Avatar


    If you can build razlomak out of integers, you don’t need to define any operators for the integer parts of the expression.

    What will happen is the int will be promoted before doing, for example

    Code:

     friend razlomak operator+( const razlomak&, const razlomak& );

    You don’t need to tell C++ how to do this beyond defining a constructor that takes an int.

    Last edited by whiteflags; 05-11-2011 at 05:55 PM.


  5. 05-11-2011


    #5

    whiteflags is offline


    Lurking

    whiteflags's Avatar


    And if you were the computer, with the expression 1+A or A+1, can you tell me, do you call the member function:

    Code:

            razlomak operator+( const razlomak& b ){
                     
                     razlomak vrati( brojnik*b.nazivnik + nazivnik*b.brojnik, nazivnik*b.nazivnik );
                              
                     return vrati;         
                              
            }

    or the free friend function:

    Code:

            friend razlomak operator+( const razlomak&, const razlomak& );

    That is why this operator, and several operators in fact, are ambiguous.


  6. 05-11-2011


    #6

    Cobs is offline


    Registered User


    Quote Originally Posted by whiteflags
    View Post

    If you can build razlomak out of integers, you don’t need to define any operators for the integer parts of the expression.

    What will happen is the int will be promoted before doing, for example

    Code:

     friend razlomak operator+( const razlomak&, const razlomak& );

    You don’t need to tell C++ how to do this beyond defining a constructor that takes an int.

    sorry I added this line after…( tried to find solution , but forgot to wrote that line like it was in original file )
    in original file it is:

    Code:

    friend razlomak operator+( int, const razlomak& );

    still dont know why operators are ambigouous.

    in: A + 1 computer should call: operator+( const razlomak& );
    in: 1 + A computer should call: friend razlomak operator+( int, const razlomak& );

    Last edited by Cobs; 05-11-2011 at 06:10 PM.


  7. 05-11-2011


    #7

    tabstop is offline


    and the Hat of Guessing

    tabstop's Avatar


    You didn’t do operator int(), but now I see operator bool() which is just as good (as far as this goes). So your razlomak’s can be converted to bool, which is an int type and therefore becomes int when you do things like + with it. So A+1 could be: bool + int or razlomak + razlomak. You want the second, but the computer isn’t able to read your mind and disallow the first.


  8. 05-11-2011


    #8

    Cobs is offline


    Registered User



  9. 05-11-2011


    #9

    laserlight is offline


    C++ Witch

    laserlight's Avatar


    Speaking of operator bool: if you are using a compiler with sufficient support for the next edition of the C++ Standard (due to be ratified this year), declare it explicit, e.g.,

    Code:

        explicit operator bool() const {
            return brojnik != 0;
        }

    Otherwise, make use of the safe bool idiom, or at least overload operator void* instead.

    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)

    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. «Finding the smallest program that demonstrates the error» is a powerful debugging tool.

    Look up a C++ Reference and learn How To Ask Questions The Smart Way


error: ambiguous overload for ‘operator=’ (operand types are ‘String’ and . )

(applies to all revisions of ArduinoJson 6)

What’s the problem?

Due to the way JsonVariant and String implement implicit type conversion, you can construct a String from a JsonVariant , but you cannot assign a JsonVariant to an existing String .

For example, in the following snippet, the first line works but the second produces a compilation error:

If you try to compile this snippet, you get the following error:

Indeed, since JsonVariant supports implicit conversion to both const char* and String , the compiler doesn’t know which constructor of String should be called, so it deems the operator as “ambiguous”.

How to solve it?

Solution 1: cast

We need to help the compiler pick the right constructor of String . One way is to cast the JsonVariant to const char* , like so:

Note that we cannot cast to String because it’s equivalent to calling the (ambiguous) constructor.

Solution 2: as ()

Another way is to use JsonVariant::as () , which explicitly converts the JsonVariant to the specified type.
For example, any of these lines would work:

Solution 3: no String

Lastly, like most String class issues, the best solution is often to replace it with a const char* or a char[] .

Indeed, the problem doesn’t exists with const char* :

Just remember that the variable name points to the value in the JsonDocument , so it’s not a copy.

Instead, if you need to make a copy you can use a char[] like so:

When you use strcpy() or strlcpy() , always provide a default value ( «» , here) because passing NULL to these functions leads to undefined behavior.

Источник

Arduino.ru

call of overloaded write is ambiguous

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

Только начал программировать. Пока написал только вот это.

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

for (byte i = 0; i Serial.write.

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

Вы предлагаете передавать данные побайтно?

» Данные послаются как один или серия байтов «

Мне нужно послать все данные массива, т.е. как серию байтов.

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

а они внутри функции всё равно побайтно передадутся. так что это полный аналог. но если очень хочется так, то вот так.

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

Пишет no matching function for call to ‘HardwareSerial::write(word*, int)’

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

Пишет no matching function for call to ‘HardwareSerial::write(word*, int)’

Ну и правильно пишет. Если у Вас массив байтов, так нафига Вы его обозвали word в 6-ой строке? Пишите byte

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

Обозвал. Снова пишет «call of overloaded ‘write(byte&, byte&)’ is ambiguous»

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

та итить колотить, поставтье наконец-то & перед Inputs.

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии
  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

Превращение значения в адрес, где оно хранится. Inputs — массив, то бишь адрес начала хранения теперь байтиков в количестве 8 шт. Квадратные скобки и чиселко в них: [0] — указание взять ЗНАЧЕНИЕ, лежащее в нулевом байтике от начала (адреса) «Inputs». А Вам надо передать в функцию не значение а адрес .. вот унарная операция & и возвращает адрес места хранения указанного значения. Правильно прочитав вышеизложенное, можно поступать «двояко»:

1. Serial .write(&(Inputs[0]), x); — получить адрес элемента массива (не обязательно 0..)

2. Serial .write(Inputs, x); — сам Inputs является адресом нулевого элемента массива (но только 0)..

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

Нашел Вашу тему.

Помогите разрешить проблему. Задача в следующем, необходимо передать значение температуры (float с 2-мя знаками после запятой) с одной ардуины на другую по UART, получается какая-то «чушь». При передаче в Serial.write значения температуры пишет, что тип float, не может передаваться. Float умножаю на 100 Перевожу в тип int (т.е 2 байта)получаю 4-х значное число, отсылаю Serial.write, на приемной стороне не получаю полную чушь. Методом проб и ошибок «вкурил», что у меня принимается только 1 байт, причем последний. Подскажите как передавать и соответственно получать через UART больше 1-го байта.

Исходный код для передатчика:

STemp_eng = 256 ; // я уже на «бубликах» пробую, не получается

Источник

Arduino.ru

call of overloaded ‘String(float&, int)’ is ambiguous

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

Здравствуйте,уважаемые гении программирования.Буду краток. Помогииите. при компиляции такая ошибка call of overloaded ‘String(float&, int)’ is ambiguous

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

381 строка ошибка

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

Версия IDE? Полная копипаста сообщения об ошибке?

И ещё, если хотите реальной помощи, всегда сокращайте пример до минимального, который показывает проблему. У меня, например, просто нет библиотеки и я не могу это скомпилировать, чтобы посмотреть. Сделайте пример без LCD и всего ненужного, но с такой же ошибкой.

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

сообщение об ошибке Arduino: 1.8.7 (Windows 10), Плата:»WAVGAT Pro mini»

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

У Вас похоже, wavgat, а у него нестандартная библиотека String

Выложите пожалуйста файл C:Program FilesArduinohardwareWAVavrcoreslgt8f/WString.h чтобы я мог на него посмотреть.

И ещё, посмотрите как Вы вставили код. Что там за глупости вначале? Из-за это поползли вес номера строк и очень трудно понимать что к чему. Старайтесь аккуратно вставлять код.

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

Да проклятый wavgat, /*

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

А вот такая ошибка при компилировании в виндовс 7 версия ардуино 1.6.8 Arduino: 1.6.8 (Windows 7), Плата:»WAVGAT Pro mini»

Источник

serial.write(byte)0) #75

the programmcode 👍
serial.write(0);
will work with arduino uno / mega

but with :
arduino 101
arduino MO
chipKIT uC32

I get an compiler error 👍

test_serial:31: error: call of overloaded ‘write(int)’ is ambiguous

use :Arduino 1.8.1
win 7

The text was updated successfully, but these errors were encountered:

In Serial.write(0); , the 0 could be interpreted as a number or as char* ( (void*)NULL in fact). The fact that AVR is not exposing this bug is quite bugging and needs some further investigation 🙂
Thanks for reporting!

In AVR, there is a write(int) overloaded method, that match exactly with write(0) , so the compiler doesn’t complain. On the other side, 101 for example has only a write(uint8_t) method, so the compiler doesn’t know if he should use that, or write(const char*) , because both require a type conversion.

I am not so sure it is a good idea to hide the fact that write takes only raw bytes by overloading it in the AVR libraries, but i guess that it was done to keep people from complaining about the ambiguous overload ;-)

@descampsa where did you find the write(int) overload?
It looks more complicated than that 😄 On any core, write(1) just works, while the const char* is evaluated as ambiguous only for 0 (which makes sense, since any non-zero number is hardly a pointer unless you cast it explicitly)

There is also the c++ quirk that only 0 is implicitly convertible to a pointer, yes, but that’s true for all platforms (unless broken compiler).

Ah, it’s in the hardware serial code, sorry, my bad 😄

A possible solution to this problem would be to declare the write(const char*) as a template in Print, and implement only the const char* version, like that (untested) :

When write(0) is called, the compiler will first look at the non-template functions, and call the uint8_t version (same for write(NULL) , but who does that?)

cousteaulecommandant commented Apr 11, 2017

Or just do in SAM what is done in AVR and add the write(int) et al methods to HardwareSerial.h.

BTW, a workaround to this particular problem is to do Serial.write(byte(0)) (which is also more elegant IMO).

Or just do in SAM what is done in AVR and add the write(int) et al methods to HardwareSerial.h.

Then you have to do it in SoftwareSerial also (and other Print derived classes, if any), for consistency.
It could be in Print, but then i guess that the compiler won’t honour the inline (to be checked), and that we don’t want another overhead on such a low level function.

BTW, a workaround to this particular problem is to do Serial.write(byte(0)) (which is also more elegant IMO).

That’s of course the simplest solution, then the write overloads should be suppressed from HardwareSerial for consistency.

Or just do in SAM what is done in AVR and add the write(int) et al methods to HardwareSerial.h.

Then you have to do it in SoftwareSerial also (and other Print derived classes, if any), for consistency.
It could be in Print, but then i guess that the compiler won’t inline the function (to be checked), and that we don’t want another overhead on such a low level function.

BTW, a workaround to this particular problem is to do Serial.write(byte(0)) (which is also more elegant IMO).

That’s of course the simplest solution, then the write overloads should be suppressed from HardwareSerial for consistency.

Then you have to do it in SoftwareSerial also (and other Print derived classes, if any), for consistency.

Then do it also in SoftwareSerial and other Print derived classes, for consistency.

Источник

Arduino Error all of overloaded ‘println(long unsigned int (&)())’ is ambiguous

Here is my code

Here is the error

Serverping.ino: In function ‘void loop()’: Serverping.ino:24:24: error: call of overloaded ‘println(long unsigned int (&)())’ is ambiguous Serverping.ino:24:24: note: candidates are: In file included from /usr/share/arduino/hardware/arduino/cores/arduino/Stream.h:26:0, from /usr/share/arduino/hardware/arduino/cores/arduino/HardwareSerial.h:28, from /usr/share/arduino/hardware/arduino/cores/arduino/Arduino.h:193, from /usr/share/arduino/libraries/SPI/SPI.h:15, from Serverping.ino:1: /usr/share/arduino/hardware/arduino/cores/arduino/Print.h:70:12: note: size_t Print::println(char) size_t println(char); ^ /usr/share/arduino/hardware/arduino/cores/arduino/Print.h:70:12: note: no known conversion for argument 1 from ‘long unsigned int()’ to ‘char’ /usr/share/arduino/hardware/arduino/cores/arduino/Print.h:71:12: note: size_t Print::println(unsigned char, int) size_t println(unsigned char, int = DEC); ^ /usr/share/arduino/hardware/arduino/cores/arduino/Print.h:71:12: note: no known conversion for argument 1 from ‘long unsigned int()’ to ‘unsigned char’ /usr/share/arduino/hardware/arduino/cores/arduino/Print.h:72:12: note: size_t Print::println(int, int) size_t println(int, int = DEC); ^ /usr/share/arduino/hardware/arduino/cores/arduino/Print.h:72:12: note: no known conversion for argument 1 from ‘long unsigned int()’ to ‘int’ /usr/share/arduino/hardware/arduino/cores/arduino/Print.h:73:12: note: size_t Print::println(unsigned int, int) size_t println(unsigned int, int = DEC); ^ /usr/share/arduino/hardware/arduino/cores/arduino/Print.h:73:12: note: no known conversion for argument 1 from ‘long unsigned int()’ to ‘unsigned int’ /usr/share/arduino/hardware/arduino/cores/arduino/Print.h:74:12: note: size_t Print::println(long int, int) size_t println(long, int = DEC); ^ /usr/share/arduino/hardware/arduino/cores/arduino/Print.h:74:12: note: no known conversion for argument 1 from ‘long unsigned int()’ to ‘long int’ /usr/share/arduino/hardware/arduino/cores/arduino/Print.h:75:12: note: size_t Print::println(long unsigned int, int) size_t println(unsigned long, int = DEC); ^ /usr/share/arduino/hardware/arduino/cores/arduino/Print.h:75:12: note: no known conversion for argument 1 from ‘long unsigned int()’ to ‘long unsigned int’

1 Answer 1

millis is a function. If you want the result of calling it then you need to call it.

Hot Network Questions

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2022 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2022.10.6.30587

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Понравилась статья? Поделить с друзьями:
  • Error already running skyrim что делать
  • Error already authenticated перевод
  • Error allocating memory что это значит
  • Error allocating memory как исправить windows 10
  • Error allocating memory gta 5