开发者

strange behavior with friend functions -- scope "globalized" when object pointer passed?

开发者 https://www.devze.com 2023-02-24 23:55 出处:网络
Let\'s say I have a header file a.h and a source file a.cpp.When I try to compile this and call what() from a different file (e.g. main.cpp) which includes a.h:

Let's say I have a header file a.h and a source file a.cpp. When I try to compile this and call what() from a different file (e.g. main.cpp) which includes a.h:


a.h:

class A {  
friend void what();  
public:  
    int index;  
};

a.cpp:

#include "a.h"
#include <iostream>

void what() {  
    std::cout << "what" << std::endl;  
}

It fails, as expected (error: 'what' was not declared in this scope). However, when I do the same thing with this:


a.h:

class A {  
friend void what(A *thing);  
public:  
    int index;  
};

a.cpp:

#include开发者_运维百科 "a.h"
#include <iostream>

void what(A *thing) {  
    std::cout << thing->index << std::endl;  
}

It compiles and runs just fine on g++ 4.4.1 (assuming "index" has been initialized, of course). I don't know much about C++, but I would assume that, by passing the object pointer to the function, the function somehow became available to the global scope (i.e. gets "promoted" in order to be able to "see" an object which previously existed on the same scope as it). I haven't tried this with other kinds of functions yet, but, when using g++ and friend functions, I get this behavior. Is this supposed to happen in C++?

Thanks and sorry if this is a noobish question, my friend Google was failing me.


I compiled your code with g++ 4.5.1 and no error was reported.


I think you have forgotten ; at the end of your class declaration.

Following code works perfectly fine for me (gcc 4.4.5)

a.h

class A {
friend void what();
private:
    int index;
};

a.cpp

#include <iostream>
#include "a.h"

using namespace std;

void what()
{
    cout << "what" << endl;
}

int main()
{
        what();
        return 0;
}

UPDATE

You should declare what function in the a.h header file before A class declaration.

0

精彩评论

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

关注公众号