关闭

深度探索C++对象模型

发表于:2012-12-25 10:22

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:宁采臣    来源:51Testing软件测试网采编

  今天这篇博文主要讲解在C++中关键字struct和class的区别。我的这篇博文,就按照系统的将这两个关键字的不同面进行详细的讲解。

  从语法上来讲,class和struct做类型定义时只有两点区别:

  (1)默认继承权限,如果不指定,来自class的继承按照private继承处理,来自struct的继承按照public继承处理;

  (2)成员的默认访问权限。class的成员默认是private权限,struct默认是public权限。以上两点也是struct和class最基本的差别,也是最本质的差别;

  但是在C++中,struct进行了扩展,现在它已经不仅仅是一个包含不同数据类型的数据结构了,它包括了更多的功能;

  首先,struct能包含成员函数吗?是的,答案是肯定的。

  好的,写一段代码验证一下:

#include "stdafx.h"
 
struct Test
{
    int a;
    int getA()
    {
        return a;
    }
 
    void setA(int temp)
    {
        a = temp;
    }
};
 
int _tmain(int argc, _TCHAR* argv[])
{
    Test testStruct;
    testStruct.setA(10);
    cout<<"Get the value from struct:"<<testStruct.getA()<<endl;
 
    Test *testStructPointer = new Test;
    testStructPointer->setA(20);
    cout<<"Get the value from struct again:"<<testStructPointer->getA()<<endl;
    delete testStructPointer;
 
    return 0;
}

  以上的代码会很正确的运行,是的;没错,struct能包含成员函数的。

  第二,struct有自己的构造函数吗?是的,可以的。

#include "stdafx.h"
struct Test
{
    int a;
 
    Test()
    {
        a = 100;
    }
 
    int getA()
    {
        return a;
    }
 
    void setA(int temp)
    {
        a = temp;
    }
};
 
int _tmain(int argc, _TCHAR* argv[])
{
    Test testStruct;
    testStruct.setA(10);
    cout<<"Get the value from struct:"<<testStruct.getA()<<endl;  Test *testStructPointer = new Test;     testStructPointer->setA(20);
    cout<<"Get the value from struct again:"<getA()<<endl;
    delete testStructPointer;
 
    // test the constructor
    Test testConstructor;
    cout<<"Set the value by the construct and get it:"<<testConstructor.getA()<<endl;
 
    return 0;
}

31/3123>
《2023软件测试行业现状调查报告》独家发布~

精彩评论

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号