DaniWeb IT Discussion Community

DaniWeb IT Discussion Community (http://www.daniweb.com/forums/index.php)
-   C++ (http://www.daniweb.com/forums/forum8.html)
-   -   Why compiler complants error when compile. (http://www.daniweb.com/forums/thread20408.html)

banbangou Mar 17th, 2005 4:03 pm
Why compiler complants error when compile.
 
Anybody could tell me what's wrong with the following code?
It complaints:
13 C:\apps\Dev-Cpp\projects\14\14_1.cpp ISO C++ forbids defining types within return type

Thanks in advance.


#include <iostream>
#include <cstdlib>

using namespace std;

struct vector {
    double x;
    double y;
   
    friend ostream& operator<< (ostream&, vector);
}   

ostream& operator<< (ostream& o, vector a) {
    o << "(" << a.x << "," << a.y << ")" << endl;
    return o;
}   

int main(int argc, char *argv[])
{
    vector v1;
    v1.x = 1;
    v1.y = 1;
   
    cout << v1 << endl;
   
    system("PAUSE");       
    return 0;
}

<< moderator edit: added [code][/code] tags >>

Dave Sinkula Mar 17th, 2005 4:16 pm
Re: Why compiler complants error when compile.
 
There will be ambiguity with your class and std::vector since you are using namespace std.
struct vector
{
  double x;
  double y;

  friend ostream& operator<< (ostream&, vector);
};
If you still want to grab the whole namespace, I think you can disambiguate like this.
friend ostream& operator<< (ostream&, ::vector);

1o0oBhP Mar 20th, 2005 10:15 pm
Re: Why compiler complants error when compile.
 
or in full "std::vector", but there is still a danger that the struct name will cause errors. Easy just to do


namespace my_vector
{
    struct vector // might as well class it
    {
        double x, y;

        friend ostream& operator<< (ostream& out, const vector& v) // I use references but its not compulsory
        {
            out << "(" << a.x << "," << a.y << ")" << endl;
            return out;
        }
    };
}

then in the main just use my_vector::vector v1; instead. This solves any name problems you might have by making your own namespace

quickhelp Apr 10th, 2005 5:05 am
Re: Why compiler complants error when compile.
 
From what I see you're missing a semicolon after the '}' from your definition of your struct.
hope this helps..


All times are GMT -4. The time now is 4:07 pm.

Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC