21xrx.com
2024-09-19 23:55:20 Thursday
登录
文章检索 我的文章 写文章
C++中的public使用方法详解
2023-10-30 01:22:46 深夜i     --     --
C++ public 使用方法 详解

在C++编程语言中,关键字public被用于声明类的公有成员。公有成员可以被类的对象和类的派生类的对象访问和使用。下面将详细讲解public关键字的使用方法。

首先,让我们看一个简单的示例来说明public关键字的作用:


class Animal {

public:

  void eat()

    cout << "Animal is eating." << endl;

  

};

在上面的示例中,eat()函数是一个公有成员函数,它可以被Animal类的对象访问和调用。我们可以创建一个Animal对象并调用eat()函数:


int main() {

  Animal animal;

  animal.eat();

  return 0;

}

输出结果为:“Animal is eating.”。

从上面的示例可以看出,公有成员函数可以在类的对象中直接调用。接下来,我们将深入探讨public关键字的一些常见用法。

首先,public关键字也可以用于声明类的公有数据成员。示例如下:


class Car

public:

  int speed;

;

在上面的示例中,speed是一个公有数据成员,它可以被Car类的对象直接访问和修改。例如,我们可以创建一个Car对象并设置speed的值:


int main()

  Car car;

  car.speed = 100;

  cout << "Car's speed is: " << car.speed << endl;

  return 0;

输出结果为:“Car's speed is: 100。”。

除了公有函数和公有数据成员,public关键字还可以用于声明类的构造函数和析构函数。示例如下:


class Person {

public:

  Person()

    cout << "Person is being created." << endl;

  

  ~Person()

    cout << "Person is being destroyed." << endl;

  

};

在上面的示例中,Person类的构造函数和析构函数都是公有的,它们可以被Person类的对象直接调用。例如,我们可以创建一个Person对象并观察构造函数和析构函数的输出:


int main()

  Person person;

  return 0;

输出结果为:“Person is being created.”和“Person is being destroyed.”。

最后需要明确的是,public关键字声明的成员可以在类的派生类中访问和调用。示例如下:


class Animal {

public:

  void eat()

    cout << "Animal is eating." << endl;

  

};

class Dog : public Animal {

public:

  void bark()

    cout << "Dog is barking." << endl;

  

};

int main() {

  Dog dog;

  dog.eat();

  dog.bark();

  return 0;

}

输出结果为:“Animal is eating.”和“Dog is barking.”。

上述示例中,Dog类是Animal类的派生类,它继承了Animal类中的公有成员函数eat()。因此,Dog类的对象可以调用eat()函数。

综上所述,在C++中,public关键字的使用方法可以总结如下:

1. 它可以用于声明类的公有成员函数和数据成员;

2. 它可以用于声明类的构造函数和析构函数;

3. 它声明的成员可以在类的对象和派生类的对象中访问和调用。

通过合理地使用public关键字,我们可以实现类的封装和继承,并提供易于使用和扩展的代码。希望本文对你理解C++中public关键字的使用方法有所帮助。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复