我正在编写 << 运算符的基本重载,因此我在类接口(interface)中添加了一个友元函数
namespace Warehouse
{
namespace Dto
{
class Product;
class AbstractOrder : public ICloneableItem
{
protected:
unsigned long _id;
std::string _name;
std::vector<Product*> _products;
public:
AbstractOrder();
virtual ~AbstractOrder();
double computePrice() const;
void addProduct(Product* product);
void removeProduct(Product* product);
void removeAllProducts();
void setName(const std::string& name) { _name = name; }
std::string getName() const { return _name; }
unsigned long getId() const { return _id; }
std::vector<Product*> getProductList() const { return _products; }
friend std::ostream& operator<<(std::ostream& os, const AbstractOrder& ord);
};
}
}
在实现文件中,这是函数的代码
using namespace Warehouse::Dto;
....
std::ostream& operator<<(std::ostream& os, const AbstractOrder& ord)
{
os << "[" << ord._id << "] Order " << ord._name << ": " << ord.computePrice();
return os;
}
为什么我收到以下错误? 错误 1 错误 C2248:“Warehouse::Dto::AbstractOrder::_id”:无法访问类“Warehouse::Dto::AbstractOrder”中声明的 protected 成员
实际上我已经修复了它,在实现文件的运算符<<之前添加了命名空间。 我不明白的是,即使在实现文件中我使用了 using namespace Warehouse::Dto 指令,为什么我也必须这样做?
最佳答案
因为operator <<
是在全局命名空间中定义的,AbstractOrder
类定义在Warehouse::Dto
中命名空间。但友元声明是针对 Warehouse::Dto
中的流运算符的。命名空间。
如果您想在全局命名空间中为运算符定义正确的友元声明,则为:
friend std::ostream& ::operator<<(std::ostream& os, const AbstractOrder& ord);
但话又说回来,您希望运算符与其流式传输的类位于同一命名空间中。
关于c++ - C2248 友元函数错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15765065/