开发者

Ambiguous Overload in cin>> operator

开发者 https://www.devze.com 2023-04-03 07:13 出处:网络
For some reason, I get an error: ambiguous operator for operator \'operator>>\' in \'std::cin>>C1\'. Declaration: ComplexNumber.h

For some reason, I get an error:

ambiguous operator for operator 'operator>>' in 'std::cin>>C1'.

Declaration: ComplexNumber.h

ostream & operator<<(ostream & out, const ComplexNumber & n);
istream & operator>>(istream & in, ComplexNumber & n);

Implementation: ComplexNumber.cpp

ostream& operator << (ostream & out, const ComplexNumber & n)
{
    n.print(out);
    return out;
}

istream& operator >> (istream & in, ComplexNumber & n)
{
    char c1[10];
    cout<<("Enter complex number: ");
    in>>c1;
    double a,b;
    a=c1[0]-'0';
    b=c1[2]-'0';
    ComplexNumber answer(a,b);
    n=answer;
    return in;
}

main.cpp

int main()
{
    ComplexNumber C1();
    cin>>C1;
    return 0;
}

compiler error

candidates are: std::basic_istream<_CharT, _Traits>::__istream_type&  std::basic_istream<_CharT, _Traits>::operator>>(std::basic_istream<_CharT,  _Traits>::__istream_type& (*)(std::basic_istream<_CharT, _Traits>::__istream_type&开发者_运维百科;)) [with _CharT = char, _Traits = std::char_traits<char>


ComplexNumber C1();

This doesn't do what you think it does.

A declaration of an object with automatic storage duration generally takes one of the following two forms:

Type name(constructor-arguments); // (1)
Type name;                        // (2)

Note that the second form does not have an empty set of parentheses (()).

That's because one of C++'s quirks is that the following declares a function called name that returns an object of type Type:

Type name();                      // (3)

Now, you didn't tell us what the candidate overloads were as listed by your compiler's diagnostic output, but evidently your declared function name can be converted to more than one target type, thus causing an "ambiguous overload" error; regardless, none of the candidates are actually what you meant.

This "problem" is known as the "Most Vexing Parse".

Instead, write:

int main() {
   ComplexNumber C1;
   cin >> C1;
}

I also recommend:

  • Indenting your code to make it legible;
  • Using std::string rather than C-style strings.


This statement:

ComplexNumber C1();

doesn't create an instance of a ComplexNumber. Instead, it declares a function called C1 that takes no arguments and returns a ComplexNumber.

See http://en.wikipedia.org/wiki/Most_vexing_parse.


ComplexNumber C1();

declares a function C1() which takes no parameters and returns a ComplexNumber.

This is called as the Most Vexing Parse in C++.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号