朋友无法使用命名空间访问私有成员

问题描述 投票:0回答:1

在重载时使用 MS Visual Studio 2019 时,我收到以下错误

operator<<

Severity    Code    Description Project File    Line    Suppression State
Error   C2248   'Instruction::Device_Impedance::m_minimum_ohms': cannot access private member declared in class 'Instruction::Device_Impedance' friend_ostream_namespace    device_impedance.cpp    13  
Severity    Code    Description Project File    Line    Suppression State
Error   C2248   'Instruction::Device_Impedance::m_maximum_ohms': cannot access private member declared in class 'Instruction::Device_Impedance' friend_ostream_namespace    device_impedance.cpp    14  

device_impedance.hpp:

#ifndef INSTRUCTION_DEVICE_IMPEDANCE_HPP
#define INSTRUCTION_DEVICE_IMPEDANCE_HPP

#include <string>
#include <iostream>


namespace Instruction
{

class Device_Impedance
{
public:
    Device_Impedance();

    Device_Impedance(const unsigned int min_ohms,
                     const unsigned int max_ohms);
       
    //! Constructor -- Copy
    Device_Impedance(const Device_Impedance&  di);
    
    //! Destructor
    ~Device_Impedance();

public:
    Device_Impedance&
    operator=(const Device_Impedance& di);

    friend std::ostream& operator<< (std::ostream& out, const Instruction::Device_Impedance&   di);
   

    //--------------------------------------------------------------------------
    //  Public Methods
    //--------------------------------------------------------------------------
public:
    const std::string&      get_name() const override;
    
    //--------------------------------------------------------------------------
    //  Private Members
    //--------------------------------------------------------------------------
private:
    unsigned int    m_minimum_ohms;
    unsigned int    m_maximum_ohms;
};


}   // End namespace Instruction

/*! @}  // End Doxygen Group
 */

#endif // INSTRUCTION_DEVICE_IMPEDANCE_HPP  

设备阻抗.cpp

#include "device_impedance.hpp"

using namespace Instruction;


/*!
 *  \details    Output the instruction name to the stream.
 */
std::ostream&
operator<< (std::ostream& out, const Instruction::Device_Impedance&   di)
{
        out << di.get_name()
//***** The next two lines are causing the error.
            << "    " << di.m_minimum_ohms
            << ", "   << di.m_maximum_ohms
            << "\n";

    return out;
}


const std::string&
Device_Impedance ::
get_name() const
{
    static std::string  instruction_name{"DEVICE_IMPEDANCE"};
    return instruction_name;
}

我的命名空间语法对于

operator<<
的实现是否正确?

c++ namespaces operator-overloading friend
1个回答
0
投票

不,你的语法不正确。

using namespace
不会导致以下声明/定义的范围位于该命名空间中。

像在标题中一样使用

namespace { /*definition here */ }
或限定定义中的名称:

std::ostream&
Instruction::operator<< (std::ostream& out, const Instruction::Device_Impedance&   di)

否则,您将定义全局

::operator<<
重载,而不是在包含该类的命名空间中声明的
friend
重载。

© www.soinside.com 2019 - 2024. All rights reserved.