954,492 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

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 >>

banbangou
Newbie Poster
3 posts since Mar 2005
Reputation Points: 10
Solved Threads: 0
 

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);
Dave Sinkula
long time no c
Team Colleague
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
 

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

1o0oBhP
Posting Pro in Training
445 posts since Dec 2004
Reputation Points: 16
Solved Threads: 6
 

From what I see you're missing a semicolon after the '}' from your definition of your struct.
hope this helps..

quickhelp
Newbie Poster
1 post since Apr 2005
Reputation Points: 10
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You