一文搞懂C和C++中struct

 1.C中struct

- 在C中struct只单纯的用作数据的复合类型,也就是说,在结构体声明中只能将数据成员放在里面,而不能将函数放在里面。

- 在C结构体声明中不能使用C++访问修饰符,如:public、protected、private 而在C++中可以使用。

- 在C中定义结构体变量,如果使用了下面定义必须加struct。

- C的结构体不能继承(没有这一概念)。

- 若结构体的名字与函数名相同,可以正常运行且正常的调用!例如:可以定义与 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;
}

 

 2.C++中struct

与C对比如下:

- C++结构体中不仅可以定义数据,还可以定义函数。

- C++结构体中可以使用访问修饰符,如:public、protected、private 。

- C++结构体使用可以直接使用不带struct。

- C++继承

- 若结构体的名字与函数名相同,可以正常运行且正常的调用!但是定义结构体变量时候只能用带struct的!

情形1:不使用typedef定义结构体别名

未添加同名函数前:

struct Student {
    
};
//void Student(){}
struct Student s; //ok
Student s;  //ok
/*上面关于s的两种方式都对,但当同时出现时会报“重定义”的错误*/

添加同名函数后:

struct Student {
    
};
void Student(){}
struct Student s; //ok
Student s;  //error

情形二:使用typedef定义结构体别名

typedef struct Base1 {         
    int v1;
    int v3;
public:     //显示声明public
    int v2;
    void print(){       
        printf("%s\n","hello world");
    };    
}B;
//void B() {}  //error! 符号 "B" 已经被定义为一个 "struct Base1" 的别名
               //C2365	“B” : 重定义;以前的定义是“typedef”

 继承案例

#include<iostream>
#include<stdio.h>
using namespace std;

struct Base
{
	Base() { cout << "Base construct" << endl; };
	//通过⽗父类指针  释放所有的⼦子类资源
	virtual ~Base() { cout << "Base deconstruct" << endl; };

	virtual void print() {
		printf("%s\n", "Base");
	};

	int v1;
private:   //error!
	int v3;
public:   //显示声明public
	int v2;	
};


struct Derived :Base 
{
	Derived() { cout << "Derived construct" << endl; };
	~Derived() { cout << "Derived deconstruct" << endl; };

public:
	int v2;
	void print() {
		printf("%s\n", "Derived");
	};
};

int main() {
	Base *b = new Derived();
	b->print();
	delete b;

	return 0;
}

 

 同名函数

#include<iostream>
#include<stdio.h>

struct Base {
	int v1;
//private:   //error!
	int v3;
public:     //显示声明public
	int v2;
	void print() {
		printf("%s\n", "hello world");
	};
};

void Base() {
	printf("%s\n", "I am Base func");
}


typedef struct Base1 {
	int v1;
//private:   //error!
	int v3;
public:     //显示声明public
	int v2;
	void print() {
		printf("%s\n", "hello world");
	};
}B;

//void B() {}  //error! 符号 "B" 已经被定义为一个 "struct Base1" 的别名

int main() {
	struct Base base;  //ok
	//Base base1;  // error!
	base.v1 = 1;
	base.v3 = 2;
	base.print();

	B b;
	b.v1 = 23;
	b.v3 = 69;
	printf("%d\n", b.v1);
	printf("%d\n", b.v3);
	Base();

	return 0;
}

 

 3.总结

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值