c/c++中的struct和class的区别

36 篇文章 0 订阅
36 篇文章 1 订阅

主要有两种情况:

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成员。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值