2016-06-27 1 views
1

boostproperty tree에 대한 설명서에는 given here 또는 libs/property_tree/examples/debug_settings.cpp 패키지의 적절한 사용 예가 나와 있습니다.(C++) 왜 boost 작성자가 클래스 대신 여기 구조체를 사용 했습니까?

내가 알고 싶은 것은 struct debug_settings 행에 관한 것입니다. 왜 이것을 클래스 대신 구조체로 만드시겠습니까? 심지어 두 개의 멤버 함수, load(...)save(...)이 있습니다. 나는 boost 작성자가 이것에 대한 좋은 이유가 있다고 가정하고 구조체와 클래스가 "기술적으로"동일한 경우에도 효율성과 관련이 있다고 생각합니다.

나열된 저작권 연도부터 C++ 98, C++ 03 또는 C++ 0x 일 가능성이 높습니다. 따라서 클래스 대신 구조체를 사용하는 이유는 적어도 사전 -C++ 11 관점.

// ---------------------------------------------------------------------------- 
// Copyright (C) 2002-2006 Marcin Kalicinski 
// 
// Distributed under the Boost Software License, Version 1.0. 
// (See accompanying file LICENSE_1_0.txt or copy at 
// http://www.boost.org/LICENSE_1_0.txt) 
// 
// For more information, see www.boost.org 
// ---------------------------------------------------------------------------- 

//[debug_settings_includes 
#include <boost/property_tree/ptree.hpp> 
#include <boost/property_tree/xml_parser.hpp> 
#include <boost/foreach.hpp> 
#include <string> 
#include <set> 
#include <exception> 
#include <iostream> 
namespace pt = boost::property_tree; 
//] 
//[debug_settings_data 
struct debug_settings 
{ 
    std::string m_file;    // log filename 
    int m_level;      // debug level 
    std::set<std::string> m_modules; // modules where logging is enabled 
    void load(const std::string &filename); 
    void save(const std::string &filename); 
}; 
//] 
//[debug_settings_load 
void debug_settings::load(const std::string &filename) 
{ 
    // Create empty property tree object 
    pt::ptree tree; 

    // Parse the XML into the property tree. 
    pt::read_xml(filename, tree); 

    // Use the throwing version of get to find the debug filename. 
    // If the path cannot be resolved, an exception is thrown. 
    m_file = tree.get<std::string>("debug.filename"); 

    // Use the default-value version of get to find the debug level. 
    // Note that the default value is used to deduce the target type. 
    m_level = tree.get("debug.level", 0); 

    // Use get_child to find the node containing the modules, and iterate over 
    // its children. If the path cannot be resolved, get_child throws. 
    // A C++11 for-range loop would also work. 
    BOOST_FOREACH(pt::ptree::value_type &v, tree.get_child("debug.modules")) { 
     // The data function is used to access the data stored in a node. 
     m_modules.insert(v.second.data()); 
    } 

} 
//] 
//[debug_settings_save 
void debug_settings::save(const std::string &filename) 
{ 
    // Create an empty property tree object. 
    pt::ptree tree; 

    // Put the simple values into the tree. The integer is automatically 
    // converted to a string. Note that the "debug" node is automatically 
    // created if it doesn't exist. 
    tree.put("debug.filename", m_file); 
    tree.put("debug.level", m_level); 

    // Add all the modules. Unlike put, which overwrites existing nodes, add 
    // adds a new node at the lowest level, so the "modules" node will have 
    // multiple "module" children. 
    BOOST_FOREACH(const std::string &name, m_modules) 
     tree.add("debug.modules.module", name); 

    // Write property tree to XML file 
    pt::write_xml(filename, tree); 
} 
//] 

int main() 
{ 
    try 
    { 
     debug_settings ds; 
     ds.load("debug_settings.xml"); 
     ds.save("debug_settings_out.xml"); 
     std::cout << "Success\n"; 
    } 
    catch (std::exception &e) 
    { 
     std::cout << "Error: " << e.what() << "\n"; 
    } 
    return 0; 
} 

I에 유래에 대한 몇 가지 이전 게시물 보았다,하지만 난 정말 찾고 있어요 것은이 경우에서만 입니다했다. 나는

내 생각 : 나에게 는 다음과 같이하지 않는다 "일반 오래된 데이터 (POD)"는 멤버 함수를 가지고 있기 때문에 클래스 기반 객체에게 std::stringstd::set을 캡슐화하기 때문이다. 그 문자열은 "불변성"에 의문을 제기 할 정도로 바뀔 수 있습니다. 그것에는 1 개 이상의 데이터 유형이 있으며 2 바이트보다 클 수 있습니다. 액세스 로딩 및 저장 기능을 통해 단순한 구조 이상의 기능을 제공합니다. Boost는 C++ 라이브러리이므로 누군가가 C 언어로 사용할 것으로 기대해서는 안됩니다.

+6

'struct'와'class'는 C++에서 동일하지만, 유일한 차이점은'struct' 속성은'public'이고'class' 속성은'private'입니다. 선택은 순전히 선호의 문제입니다. – Holt

+0

@Holt 그들이 "동등"하다는 것을 알고 있지만, 아마도 결과 머신 코드가 ++/++처럼 다양 할 수 있다고 생각했습니다.아니면 순전히 스타일 일 경우, 그들의 추론은 무엇이었습니다. –

+0

기본 액세스 지정자를 제외하고 동일하면 기계 코드가 다른 이유는 무엇입니까? 구조체/클래스에 중복 된'public :'을'public :'앞에두면 머신 코드가 달라질 것이라고 기대하십니까? –

답변

6

이 클래스는 데이터를 캡슐화하지 않습니다. 단순히 그것을 함께 모은다. 편의 기능과 함께 수업의 요점으로 보입니다.

class debug_settings 
{ 
public: 
    std::string m_file;    // log filename 
    int m_level;      // debug level 
    std::set<std::string> m_modules; // modules where logging is enabled 
    void load(const std::string &filename); 
    void save(const std::string &filename); 
}; 

을하지만 그들은 모든 것을 어쨌든 대중 경우가 클래스를 필요로하지 않는 결정 :

5

그들은이 작업을 수행 할 수 있습니다.

As it was already said:

구조체와 클래스 C++에서 동일

는 유일한 차이점은 클래스 속성은 개인 동안 기본적으로 구조체의 속성이 공개되어 있다는 점이다.

관련 문제