<分区>
考虑到这个片段,正如预期的那样,当调用流运算符而不指定命名空间时(通过像 1 一样调用流运算符),gcc 无法找到在 NA::operator<< 和 NB::operator<< 之间选择哪个符号。可以明确地调用 NB::operator<<(如 2)。这运行并具有预期的行为。但是当尝试对 friend stream operator(如 3)执行相同操作时会出现构建错误,告知 operator<< 不是 NA 的成员。为什么? NA::operator<< 似乎是在 case 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<< ?