在boost 属性树的文档中,有一个正确使用的示例,在此处或在包中给出 libs/property_tree/examples/debug_settings.cpp.
我想知道的是关于这struct debug_settings条线.为什么要把它作为结构而不是类?它甚至有两个成员函数,load(...)和save(...).我认为提升作者有充分的理由这样做,并且它与...效率有某种关系,即使结构和类在"技术上"相同?
从列出的版权年份,我可以猜测这可能是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 = …Run Code Online (Sandbox Code Playgroud) 在C++中声明结构有没有优势?为什么我不应该只创建一个只包含数据成员的类(即没有方法)?
谢谢,
所以通常我不会问这样的问题,因为它似乎可能是基于意见的,或者对编码实践发起某种口头战争,但我认为这里可能有一个我不明白的技术原因。
我正在查看 vcpkg(微软正在创建的库打包管理器,是“新”代码)的头文件中的代码,因为阅读代码通常是学习您不知道的东西的好方法。
我注意到的第一件事是使用using而不是typedef。
来自“ https://github.com/microsoft/vcpkg/blob/master/toolsrc/include/vcpkg/parse.h ”的片段
template<class P>
using ParseExpected = ExpectedT<std::unique_ptr<P>, std::unique_ptr<ParseControlErrorInfo>>;
Run Code Online (Sandbox Code Playgroud)
我之前没有亲自使用过using这种方式,答案来自:What is the Difference Between 'typedef' and 'using' in C++11? 。本质上,using是一种新的实现方式,好处是可以使用模板。所以微软有充分的理由使用using而不是typedef.
看着' https://github.com/microsoft/vcpkg/blob/master/toolsrc/include/vcpkg/commands.h '我注意到他们没有使用任何类。相反,它只是其中包含函数等的名称空间。IE:
namespace vcpkg::Commands
{
namespace BuildExternal
{
void perform_and_exit(const VcpkgCmdArguments& args, const VcpkgPaths& paths, const Triplet& default_triplet);
}
}
Run Code Online (Sandbox Code Playgroud)
我猜测其中的一部分是调用语法看起来本质上就像类中的静态成员函数,因此代码执行相同的操作,但可能通过作为命名空间而不是类来节省一些开销。(如果有人对此也有任何想法,那就太好了。)
现在是这一切的要点。为什么 Microsoft 在其命名空间中使用结构而不是类?
来自“ https://github.com/microsoft/vcpkg/blob/master/toolsrc/include/vcpkg/parse.h ”的片段:
namespace vcpkg::Parse
{
/* ... Code I'm excluding for brevity ... */
struct …Run Code Online (Sandbox Code Playgroud) 我必须使用SDL为我的年终项目构建一个视频游戏.但是我对于如何以及何时使用类有点迷茫.
T试图在一个类中包含一个变量类型的结构但我无法做到这一点,也许Position应该是一个类而不是一个结构?这是我的代码:
struct Position{
int x,y;
};
class Object{
private:
Position pos;
Position speed;
int tipe;
public:
Objeto(int,int);
Objeto();
~Objeto(); // DESTROY
};
Run Code Online (Sandbox Code Playgroud)
当我尝试这样做时,我得到错误:'class Object' has no member named 'x'如何在对象中包含结构?