1.struct内不能定义成员函数
include<stdio.h>
struct s
{
int x; //正确
void print(); //错误
};
int main()
{}
错误:字段‘print’声明为一个函数
void print();
2.struct成员默认为public, class成员默认为private
include<stdio.h>
include<string.h>
struct s
{
int x;
char name[20];
}s1;
int main()
{
s1.x=18;
strcpy(s1.name, "bzz"); //正确
printf("%s:%d\n", s1.name, s1.x);
}
输出:bzz:18
include<bits/stdc++.h>
using namespace std;
class s
{
int x;
}s1;
int main()
{
s1.x=5; //错误
}
报错:
test.cpp:6:6: 错误:‘int s::x’是私有的
int x;
^
test.cpp:11:5: 错误:在此上下文中
s1.x=5;
3.struct不可以设为空 class 可以
include<stdio.h>
include<string.h>
struct s
{
int x;
char name[20];
}s1;
int main()
{
struct s *s2=NULL; //错误
}
报错:
test.c: 在函数‘main’中:
test.c:10:9: 错误:无效的初始值设定
struct s s2=NULL;
4.class可以定义析构器,但是struct不可以
include<stdio.h>
include<string.h>
struct CTest
{
CTest();
~CTest(); //错误
int num;
};
int main()
{
}
报错:
test.c:5:5: 错误:expected specifier-qualifier-list before ‘CTest’
CTest();
^
-
class可以有显式的无参构造器,但是struct不可以
public struct structA
{
//public int A = 90; //错误:“structA.A”: 结构中不能有实例字段初始值
public int A;
//public structA() //错误:结构不能包含显式的无参数构造函数
//{
// this.A = 0;
//}public structA(int paraA) //ok
{
this.A = paraA;
}
}
public class classA
{
public int A = 90;
public classA()
{
this.A = 90;
}
}
网友评论