C++ class与struct的区别

在C语言中,struct是作为数据类型存在的,因此其中只能包含变量,不可以包含函数,结构相对简单。而C++采用OOP编程思想,为struct扩充了很多属性,使得C++中的struct与class非常相似,而区别主要体现在默认权限上。

先来看一个例子:

#include<iostream>
#include<string>
using namespace std;

struct Student
{
	//可以拥有构造函数(非必须)
	Student(string name, int age) :m_name(name), m_age(age) {};
	//可以拥有函数(非必须)
	void show() { cout << "name: " << m_name << ", age: " << m_age << endl; };

	string m_name;
	int m_age;
};

//可以继承
struct Super_Student :public Student
{
	Super_Student(string name, int age, float score) :Student(name, age), m_score(score) {};
	void show()
	{
		cout << "This is a Super_Student." << endl;
		//可以使用基结构体中的成员
		cout << "name: " << m_name << ", age: " << m_age << ", score: " << m_score << endl;
	}
	float m_score;
};

int main(void)
{
	Student stu1("Alice", 23);
	stu1.show();
	cout << "访问结构体成员: " << endl;
	cout << "name: " << stu1.m_name << ", age: " << stu1.m_age << endl;

	Super_Student stu2("Ben", 20, 99.9);
	stu2.show();

	return 0;
}

运行结果:

name: Alice, age: 23
访问结构体成员:
name: Alice, age: 23
This is a Super_Student.
name: Ben, age: 20, score: 99.9

在该例子中我定义了两个结构体Student和Super_Student,可以看到作为结构体的Student也可以定义构造函数和一般函数,Super_Student则体现了结构体也可以继承的特性。

struct与class的主要区别在于默认权限方面:

  1. class的成员默认权限为private,struct的成员默认权限为public。因此在主函数中可以直接通过stu1.m_name来访问到Student的成员变量。
  2. class的继承默认是private继承,struct的继承默认是公有继承。因此在Super_Student中的show()函数可以使用Student中的成员。

除此之外,在模板的使用方面:

  1. class可以作为一个关键字定义模板参数(与typename作用一样),而struct不可以
  2. class和struct都可以使用模板。比如STL中的很多容器就用到了模板结构体。

版权声明:本文为Kallou原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。