主要有两种情况:
1.C语言中的struct和c++中的class区别。
2.c++中的struct和c++中的class的区别。
下面分别介绍:
1.C语言中的struct和c++中的class的区别
C语言中的struct只能定义成员变量,不能够定义成员函数。如下所示:
struct point
{
int x;
int y;
void print()
{
printf("hello\n");//compile error
}
}
2.c++中的struct和class的区别。-----对默认成员的访问权限和继承方式的不同
在c++中的struct有构造函数和成员函数。并且有class的其它特性。c++中的struct中默认的成员是public的,而class中成员默认是private的,如下代码:
#include "stdafx.h"
#include <iostream>
//#include <struct_class.h>
using namespace std;
class test_class
{
int x;
int y;
void print()
{
cout << "ptint output x,y = " << x << y << endl;
}
public:
test_class(int x, int y)
{
this->x = x;
this->y = y;
}
void print1()
{
cout << "print1 output x,y = " << x << y << endl;
}
};
struct test_struct
{
int x;
int y;
void print()
{
cout << "class ptint output x,y = " << x << y << endl;
}
test_struct(int x, int y)
{
this->x = x;
this->y = y;
}
private:
void print1()
{
cout << "class ptint1 output x,y = " << x << y << endl;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
cout << "hello" << endl;
test_class class_a(2,3);//调用test_class带参数的构造函数
test_struct struct_b(5,6);//调用test_struct带参数的构造函数
class_a.print1();
struct_b.print();
while (1);
return 0;
}
从继承角度看,class继承默认是private继承,而struct的继承是public继承。以private方式继承父类的子类对象不能访问父类的public成员。