title: struct
date: 2021-06-20 19:39:59
tags:
struct
C 中 struct
- C 的结构体不能继承(没有这一概念)。
- 在 C 中定义结构体变量,如果使用了下面定义必须加 struct。
- 在 C 结构体声明中不能使用 C++ 访问修饰符,如:public、protected、private 而在 C++ 中可以使用。
- 在 C 中 struct 只单纯的用作数据的复合类型,也就是说,在结构体声明中只能将数据成员放在里面,而不能将函数放在里面。
- 若结构体的名字与函数名相同,可以正常运行且正常的调用。例如:可以定义与 struct Base 不冲突的 void Base() {}。
完整案例:
#include<stdio.h>
struct Base { // public
int v1;
// public: //error
int v2;
//private:
int v3;
//void print(){ // c中不能在结构体中嵌入函数
// printf("%s\n","hello world");
//}; //error!
};
void Base() {
printf("%s\n", "I am Base func");
}
//struct Base base1; //ok
//Base base2; //error
int main() {
struct Base base;
base.v1 = 1;
//base.print();
printf("%d\n", base.v1);
Base();
return 0;
}
最后输出:
1
I am Base func
C++ 中 struct
与 C 对比如下:
- C++ 继承。
- C++ 结构体没有同名函数时,可以直接使用不带 struct。
- C++ 结构体中可以使用访问修饰符,如:public、protected、private 。
- C++ 结构体中不仅可以定义数据,还可以定义函数。
- 若结构体的名字与函数名相同,可以正常运行且正常的调用。但是定义结构体变量时候只用用带 struct 的。
有无同名函数
没有同名函数时,可以直接使用不带 struct
struct Student {
};
//Student() {};
struct Student s; //ok
Student s; //ok
添加同名函数后
struct Student {
};
void Student() {};
struct Student s; //ok
Student s; //error
使用 typedef 定义结构体别名
typedef struct Base1 {
int v1;
private:
int v3;
public:
int v2;
void print() {
printf("%s\n", "hello world");
};
}B;
//void B() {} //error! 符号 "B" 已经被定义为一个 "struct Base1" 的别名
综合案例
#include<iostream>
#include<stdio.h>
struct Base {
int v1;
private:
int v3;
friend int main();
public:
int v2;
void print() {
printf("%s\n", "hello world");
};
};
int main() {
struct Base base1; //ok
Base base2; //ok
Base base;
base.v1 = 1;
base.v3 = 2;// 私有的外部不可访问,加上友元后可访问
base.print();
printf("%d\n", base.v1);
printf("%d\n", base.v3);// 私有的外部不可访问,加上友元后可访问
return 0;
}
继承案例
#include<iostream>
#include<stdio.h>
struct Base {
int v1;
private:
int v3;
public: //显示声明public
int v2;
virtual void print() {
printf("%s\n", "Base");
};
};
struct Derived : Base {
public:
int v2;
void print() {
printf("%s\n", "Derived");
};
};
int main() {
Base* b = new Derived();
b->print();
return 0;
}
同名函数
#include<iostream>
#include<stdio.h>
struct Base {
int v1;
private:
int v3;
friend int main();
public:
int v2;
void print() {
printf("%s\n", "hello world");
};
};
typedef struct Base1 {
int v1;
private:
int v3;
public:
int v2;
void print() {
printf("%s\n", "hello world");
};
}B;
void Base() {
printf("%s\n", "I am Base func");
}
//void B() {} //error! 符号 "B" 已经被定义为一个 "struct Base1" 的别名
int main() {
struct Base base; //ok
//Base base1; // error!
base.v1 = 1;
base.v3 = 2;
base.print();
printf("%d\n", base.v1);
printf("%d\n", base.v3);
Base();
return 0;
}
总结
C 和 C++ 中的 struct 区别
C | C++ |
---|---|
不能将函数放在结构体声明 | 能将函数放在结构体声明 |
在 C 结构体声明中不能使用 C++ 访问修饰符。 | public、protected、private 在 C++ 中可以使用。 |
在 C 中定义结构体变量,如果使用了下面定义必须加 struct。 | 可以不加struct |
结构体不能继承(没有这一概念)。 | 可以继承 |
若结构体的名字与函数名相同,可以正常运行且正常的调用。 | 若结构体的名字与函数名相同,使用结构体,只能使用带 struct 定义。 |
PDF:链接 密码:dqny