首页 > 解决方案 > 将结构与方法与函数和类一起使用之间的区别?

问题描述

最近我看到一个用 C++ 编写的 github 项目,它用structs.

例子:

struct Example
{
    std::string message;

    Example() 
    {
        message = "foo";
    }

    void setMessage(std::string newMsg)
    {
        message = newMsg;
    }

    void getMessage(std::string newMsg)
    {
        return message;
    }
}

struct在研究中,我发现定义对象和定义对象的区别在于class:在中struct,方法、函数和属性默认是公共的,class同样默认是私有的。

我的问题是:使用结构比使用类有什么好处?

标签: c++

解决方案


推荐阅读