繁体   English   中英

避免在hpp文件中公开私有成员变量

[英]Avoid exposing private member variables in hpp files

我已经实现了一个类buffer_manager 这个类的目的是为我的udp_clienttcp_client应用程序提供缓冲区。

buffer_manager.hpp

#ifndef BUFFER_MANAGER_H
#define BUFFER_MANAGER_H

#include <iostream>
#include <exception>
#include <boost/array.hpp>
#include <boost/algorithm/hex.hpp>
#include <algorithm>
#include <iomanip>


class buffer_manager
{
public:
    typedef boost::array<unsigned char, 4096> m_array_type;
    buffer_manager();
    ~buffer_manager();
    void message_buffer(m_array_type &recv_buf);
    buffer_manager::m_array_type & get_recieve_array();
    std::string & get_message_string();

private:
  std::string m_message;
  m_array_type m_recv_buf;
};

#endif //BUFFER_MANAGER_H   

buffer_manager.cpp

#include <iostream>                                                                                                                                                                                                
#include <boost/array.hpp>
#include <boost/algorithm/hex.hpp>
#include <algorithm>
#include "buffer_manager.hpp"

buffer_manager::buffer_manager()
{

}
buffer_manager::~buffer_manager()
{

}
void buffer_manager::message_buffer(m_array_type &recv_buf)
{
    boost::algorithm::hex(recv_buf.begin(), recv_buf.end(), back_inserter(m_message));
}

buffer_manager::m_array_type& buffer_manager::get_recieve_array()
{
  return m_recv_buf;
}

std::string & buffer_manager::get_message_string()
{
  return m_message;
}

有人告诉我,如果你不打算继承这个类,就不需要在头文件中公开成员变量了。

std::string m_message;
m_array_type m_recv_buf;

如果不在头文件中公开私有成员变量,这样做的选项是什么? 这种方法有什么好处。

这不太正确。 有些技术更先进(如pimpl习语或虚拟基类),但对于正常使用,它们必须位于头文件中。

这样做的方法是将私有变量移动到.cpp文件。 翻译单元中的任何静态全局变量基本上都是“私有的”,因为无法从其他文件访问它们。 理由(据我所知)是,当您阅读头文件以进行概要时,认知负荷较少。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM