加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 如何明确地调用朋友流操作符?

发布时间:2020-12-16 07:23:42 所属栏目:百科 来源:网络整理
导读:参见英文答案 Is ADL the only way to call a friend inline function?????????????????????????????????????3个 考虑到这个片段,正如预期的那样,gcc无法找到NA :: operator和NB ::运算符调用流操作符而不指定命名空间(通过调用流操作符,如1)).可以调用NB ::
参见英文答案 > Is ADL the only way to call a friend inline function?????????????????????????????????????3个
考虑到这个片段,正如预期的那样,gcc无法找到NA :: operator<<和NB ::运算符<<调用流操作符而不指定命名空间(通过调用流操作符,如1)).可以调用NB :: operator<<明确地(如2).这会运行并具有预期的行为.但是当尝试对朋友流操作符(如3)执行相同操作时会引发构建错误,告诉操作符<<不是NA的成员.为什么?
NA ::操作符LT;<似乎在案例1)中找到…

#include <iostream>
#include <vector>

#include <fstream>

namespace NA {
    class A {
        friend inline std::ostream & operator<<(std::ostream & s,const A & object) {
            std::cout << "NA::operator<<" << std::endl;
            return s;
        }
    };
}

namespace NB {
    std::ostream & operator<<(std::ostream & s,const NA::A & object) {
        std::cout << "NB::operator<<" << std::endl;
        return s;
    }
    void func(const NA::A* a);
}

void NB::func(const NA::A* a) {
    std::ofstream ofs;
    //1)
    //ofs << *a; //build error:
    //error: ambiguous overload for 'operator<<' (operand types are 'std::ofstream' {aka 'std::basic_ofstream<char>'} and 'const NA::A')
    //2)
    //NB::operator<<(ofs,*a); //runs and displays NB::operator<<
    //3)
    NA::operator<<(ofs,*a); //build error:
    //error: 'operator<<' is not a member of 'NA'
}

int main()
{
    NA::A obj_a;
    NB::func(&obj_a);
}

我的问题是,如何明确地调用NA :: operator<< ?

解决方法

这个cas有点奇怪.

对于此代码:

ofs << *a;

编译器明确指出两者之间存在歧义:

main.cpp:16:20: note: candidate: 'std::ostream& NB::operator<<(std::ostream&,const NA::A&)'
     std::ostream & operator<<(std::ostream & s,const NA::A & object) {
                    ^~~~~~~~

main.cpp:8:38: note: candidate: 'std::ostream& NA::operator<<(std::ostream&,const NA::A&)'
         friend inline std::ostream & operator<<(std::ostream & s,const A & object) {
                                      ^~~~~~~~

但是当明确地调用运算符时

NA::operator<<(ofs,*a);

编译器找不到它:

main.cpp:39:17: error: 'operator<<' is not a member of 'NA'
    NA::operator<<(ofs,*a);
                ^~

我找到的唯一解决方法是在名称空间NA中声明一个函数,该函数将调用运算符,然后编译器能够选择好的函数:

namespace NA {
    void print_it(std::ofstream & os,const A & a)
    {
        os << a;
    }
}

好的,我得到了@Passer By的评论

声明函数不会被编译器查找,添加方法的前向声明,如:

namespace NA {
    class A;
    std::ostream & operator<<(std::ostream & s,const A & object);
}

允许编译器找到声明,因此

NA::operator<<(ofs,*a);

将由编译器解决.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读