21xrx.com
2025-03-22 20:29:56 Saturday
文章检索 我的文章 写文章
C++类的定义方式
2023-07-14 04:24:43 深夜i     11     0
C++ 定义方式

C++是一种高级编程语言,它的面向对象编程是其强大的功能之一。在C++中,类是一种抽象数据类型,它允许程序员将数据和操作捆绑在一起,形成一个自包含的单元。定义类是C++面向对象编程的基础之一。本文讨论C++类的定义方式。

在C++中,类可以通过以下方式定义:

1. 类名

可以通过关键字class或struct定义一个类。

class Car
{
public:
  int num;
  string color;
  void run();
};

在上面的代码中,我们定义了一个名为Car的类,它包含一个int类型的num变量和一个string类型的color变量,以及一个名为run的函数。

2. 访问控制

访问控制是指类的成员可以被哪些代码访问。C++中有三种访问控制修饰符:public、protected和private。

class Car
{
public:
  int num; // 公有的变量
public:
  void run(); // 公有的函数
protected:
  void stop(); // 受保护的函数
private:
  string color; // 私有的变量
};

在上面的代码中,我们定义了一个名为Car的类,它包含一个公有的int类型变量num和一个公有的名为run的函数、一个受保护的名为stop的函数和一个私有的string类型变量color。

3. 成员函数

成员函数是指可以访问类的私有变量的函数。

class Car
{
public:
  int num;
  string color;
public:
  void run();
private:
  void stop();
};
void Car::run() // 定义成员函数
  cout << "The car with num " << num << " are running!" << endl;
void Car::stop() // 定义成员函数
  cout << "The car with color " << color << " should stop!" << endl;

在上面的代码中,我们定义了两个成员函数,分别是run()和stop()。

4. 构造函数

构造函数是指在类实例化的时候自动调用的函数。

class Car
{
public:
  int num;
  string color;
public:
  Car(); // 默认构造函数
  Car(int n, string c); // 构造函数
  void run();
};
Car::Car() // 默认构造函数
  num = 0;
  color = "white";
Car::Car(int n, string c) // 定义构造函数
  num = n;
  color = c;

在上面的代码中,我们定义了两个构造函数,一个是默认构造函数,它没有参数;另一个是有参数的构造函数。

5. 析构函数

析构函数是指在类实例销毁时自动调用的函数。

class Car
{
public:
  int num;
  string color;
public:
  Car();
  ~Car(); // 析构函数
  void run();
};
Car::~Car() // 定义析构函数
  cout << "The car with num " << num << "will be destroyed!" << endl;

在上面的代码中,我们定义了一个析构函数。

以上就是C++类的定义方式,学习这些内容可以帮助你更好地理解和使用面向对象编程。

  
  

评论区