C++中关键字Struct和Class的区别

2020-01-06 12:58:02于海丽

Struct有自己的构造函数吗?

是的,可以的。看以下测试代码:

 

复制代码
/*
** FileName     : StructAndClassDiffDemo
** Author       : Jelly Young
** Date         : 2013/12/7
** Description  : More information, please go to http://www.easck.com/> */
 
#include <iostream>
using namespace std;
 
struct Test
{
    int a;
 
    Test()
    {
        a = 100;
    }
 
    int getA()
    {
        return a;
    }
 
    void setA(int temp)
    {
        a = temp;
    }
};
 
int main(int argc, char* 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:"<<testStruct.getA()<<endl;
    delete testStructPointer;
 
    // test the constructor
    Test testConstructor;
    cout<<"Set the value by the construct and get it:"<<testConstructor.getA()<<endl;
 
    return 0;
}

 

Struct可以有析构函数么?

让我来验证一下:

 

复制代码
/*
** FileName     : StructAndClassDiffDemo
** Author       : Jelly Young
** Date         : 2013/12/7
** Description  : More information, please go to http://www.easck.com/> */
 
#include <iostream>
using namespace std;
 
struct Test
{
    int a;
 
    Test()
    {