c++ - C2248 友元函数错误

标签 c++ visual-c++

我正在编写 << 运算符的基本重载,因此我在类接口(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/

相关文章:

c++ - 为什么::feof() 不同于::_eof(::fileno())?

c++ - 如何在ubuntu上安装METIS

c++ - 将 std::function 作为参数传递时出现问题

c++ - 为什么这个 static_cast 是不允许的?

c++ - 在字符串的情况下,在 C++ 中重载 = 运算符

c++ - c/c++ for windows 中的 DNS 服务器

c++ - 无法理解逗号运算符的工作原理

c++ - 禁用 GCC 自动并行化

.net - 如何检测 .NET 应用程序是否正在使用我的 COM 对象?

c++ - 结束使用 ShellExecute 函数启动的 C++ 程序的最佳方法是什么?