C++ 有没有办法在类内部而不是作为类的朋友重载提取操作符?

C++ 有没有办法在类内部而不是作为类的朋友重载提取操作符?,c++,operator-overloading,friend-function,C++,Operator Overloading,Friend Function,我试图超载这里有一个例子: #include <iostream> #include <string> using namespace std; class A { public: string pr() { return "Hi, I'm class A"; } }; ostream &operator << (ostream &o, const A &a) { o << a.pr(); re

我试图超载这里有一个例子:

#include <iostream>
#include <string>

using namespace std;

class A {
public:
    string pr() { return "Hi, I'm class A"; }
};

ostream &operator << (ostream &o, const A &a) {
    o << a.pr();
    return o;
}

int main() {
    A a;

    cout << a << endl;

    return 0;
}
#包括
#包括
使用名称空间std;
甲级{
公众:
string pr(){return“嗨,我是A类”;}
};

ostream&operator我们通常使用的C++被设计为允许非成员函数执行在其他语言中需要成员函数的操作。
friend
函数与成员函数非常相似,因为它可以在类范围内定义。另外(这可能会让人困惑)如果只在类范围内声明
friend
函数,则只能通过向其传递该类的对象来访问它

struct printme {
    friend std::ostream &operator<< ( std::ostream &os, printme const & )
        { return os << "hello"; }

    friend void named_friend( printme const & ) {}
};

std::cout << printme(); // OK
named_friend( printme() ); // OK
void (*fn_ptr) = named_friend; /* function not found
           it can only be found by association with printme */
struct printme{

friend std::ostream&Operator请看这个关于如何在类中定义friend的答案,为什么这会很重要?我的意思是,既然这不重要(我认为),这个问题就没用了(因此值得否决)。如果这很重要,了解它为什么重要会有帮助,因为这样一来,人们就可以尝试用其他方式来解决问题,而不是试图用一种不可能的方式来解决问题。@R.MartinhoFernandes我认为这是一个好问题,基本上他想以非直观的方式实现ADL所做的事情。这个问题有些模糊,很难公式化我真的看不懂这个问题。如果是这样的话,我仍然认为OP需要澄清这一点。具体地说,我认为他正在创建一个只包含标题的库,并希望删除他认为是“用户”的
.cpp
组件这也可以通过定义所述的好友来实现,但要使其内联,我的答案更好:v)请在创建帖子时观察预览…然后按
{}
按钮引用源代码。非常感谢:)我最近尝试使用boost,同时,我看到了很多这种重载,这让我的生活变得非常简单,特别是在使用boost::serialize时,然后我想,为什么我不自己做这件事,让我喜欢的东西更简单?:)是的,你是对的,我从来没有想过解决这个问题。我一定会记住这一点:)再次谢谢你,先生:)
myobject<<cout;
cout<<myobject 
struct printme {
    friend std::ostream &operator<< ( std::ostream &os, printme const & )
        { return os << "hello"; }

    friend void named_friend( printme const & ) {}
};

std::cout << printme(); // OK
named_friend( printme() ); // OK
void (*fn_ptr) = named_friend; /* function not found
           it can only be found by association with printme */