在 C 语言 中,结构体 只能存放一些 变量 的集合,并不能有 函数,但 C++ 中的结构体对 C 语言中的结构体做了扩充,可以有函数,因此 C++ 中的结构体跟 C++ 中的类很类似。C++ 中的 struct 可以包含成员函数,也能继承,也可以实现多态。
但在 C++ 中,使用 class 时,类中的成员默认都是 private 属性的,而使用 struct 时,结构体中的成员默认都是 public 属性的。class 继承默认是 private 继承,而 struct 继承默认是 public 继承。
C++ 中的 class 可以使用模板,而 struct 不能使用模板。
C++类和结构体的区别
#include <iostream>
using namespace std;
class Student
{
Student(string name, int age)
{
this->m_name = name;
this->m_age = age;
}
void sayHello() const
{
cout << "I am " << this->m_name << " and i am " << this->m_age << " years old!" << endl;
}
string m_name;
int m_age;
};
void show(Student stu)
{
cout << "Call Show, Name =" << stu.m_name << " Age = " << stu.m_age << endl;
}
int main()
{
cout << "嗨客网(www.haicoder.net)\n" << endl;
Student stu("HaiCoder", 111);
show(stu);
return 0;
}
程序运行后,控制台输出如下:
我们可以看到,类中的所有的成员我们都没有使用修饰符修饰,此时,是默认的 private,因此,我们在函数外部访问其成员,程序报错,现在,我们将程序修改如下:
#include <iostream>
using namespace std;
struct Student
{
Student(string name, int age)
{
this->m_name = name;
this->m_age = age;
}
void sayHello() const
{
cout << "I am " << this->m_name << " and i am " << this->m_age << " years old!" << endl;
}
string m_name;
int m_age;
};
void show(Student stu)
{
cout << "Call Show, Name =" << stu.m_name << " Age = " << stu.m_age << endl;
}
int main()
{
cout << "嗨客网(www.haicoder.net)\n" << endl;
Student stu("HaiCoder", 111);
show(stu);
return 0;
}
程序运行后,控制台输出如下:
我们可以看到,我们只是将 class 修改为了 struct,此时,我们可以在外部访问其成员,因为 struct 默认的成员全是 public 的,因此可以在类外部访问。
在 C++ 中,使用 class 时,类中的成员默认都是 private 属性的,而使用 struct 时,结构体中的成员默认都是 public 属性的。class 继承默认是 private 继承,而 struct 继承默认是 public 继承。
C++ 中的 class 可以使用模板,而 struct 不能使用模板。