C++类的概念
在C++中,类是一种用户自定义的数据类型,它可以包含数据成员和函数成员。
类的定义使用关键字class或者struct,语法如下:
class class_name {
access_specifier:
member1;
member2;
access_specifier:
member3;
member4;
...
} object_names;
其中,class_name是类名,access_specifier是访问成员的权限(public、protected、private),member1、member2等是该类的成员变量和成员函数,object_names是这个类的对象名。
例如,我们定义一个名为Student的类,其中包含公有成员函数printName和私有成员变量name。
#include <iostream>
#include <string>
using namespace std;
class Student {
public:
void printName(){
cout << name << endl;
}
private:
string name = "张三";
};
int main() {
Student st;
st.printName(); // 输出 "张三"
return 0;
}
在这个例子中,我们创建了一个Studen
C++中的类是一种用户自定义数据类型,包含数据成员和函数成员。类定义使用class或struct关键字,通过访问修饰符(public、protected、private)来控制成员的访问权限。例如,创建一个Student类,拥有printName函数和私有变量name。类是面向对象编程的基础,C++的类支持使得程序设计更为高效和灵活。
订阅专栏 解锁全文
465

被折叠的 条评论
为什么被折叠?



