栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++ struct和class区别

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++ struct和class区别

在C++中struct和class唯一的区别就在于默认的访问权限不同。
区别:
1)struct默认全为公共;
2) class 默认为私有;

#include 
using namespace std;

class C1
{
    int m_A;//默认为私有
};

struct C2
{
    int m_A;//默认全为公共
};

int main()
{
    

    C1 c1;
    //c1.m_A=100;

    C2 c2;
    c2.m_A = 100;
    system("pause");
    return 0;
}

2、成员属性设置为私有
优点:
1)、将所有成员属性设置为私有,可以自己控制读写权限;
2)、对于写权限,我们可以检测数据的有效性;

#include 
#include
using namespace std;



//设计人类
class Person
{
public:
    void setName(string name)
    {
        m_Name = name;
    }
    string getName()
    {
        return m_Name;
    }

    int getAge(int age)
    {
        if (age < 0 || age>150)
        {
            cout << "你这个老妖精" << endl;
            return;
        }
        m_Age = 0;
        return m_Age;
    }

    void setLover(string lover)
    {
        m_Lover = lover;
    }

private:
    string m_Name;
    int m_Age;
    string m_Lover;
};

int main()
{
    Person p;
    p.setName("张三");
    cout << "姓名为:" << p.getName() << endl;

    p.setLover("苍劲");
    //cout << "情人是:" << p.setLover() << endl;

    cout << "年龄为:" << p.getAge() << endl;
    system("pause");
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/297657.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号