C ++教程:类和对象

来源:互联网 发布:大逆之门txt知白下载 编辑:程序博客网 时间:2024/05/28 11:48

C++ Tutorial: Classes and Objects

在本教程中,我们将介绍C ++中的面向对象编程。 这里,我们将看看类和对象及其各个组件。 我们将看看类操作的基本类型,例如构造函数,析构函数,setter和getter。 最后,我们将关注私人,公共和受保护的关键词。

在这个页面的底部,你会发现一个完整的工作程序的代码,将演示对象如何工作。 将代码复制粘贴到您自己的项目或从Github下载程序文件.

什么是面向对象编程?

面向对象编程是一种编程方法,专注于将数据和函数建模为对象。 相比之下,程序性规划重点关注程序执行,逐条语句。 在某种程度上,面向对象的编程更抽象,而过程编程更接近原始机器指令。

OOP_PPP (13)

为什么要学习面向对象的编程?

面向对象的编程对现代计算至关重要。 面向对象编程不仅仅专注于完成任务,还允许您构建反映“现实世界”的模型和关系。

     1.应用程序开发:面向对象编程是今天大多数应用程序是如何。 它是必不可少的游戏编程和做你可能在手机或平板电脑上使用的那种应用程序。

    2.向下设计:面向对象的编程是一种以高效和直观的方式设计程序的好方法。 对象给你一个高层次的概念开始,所以你可以先设计和代码。
    3.代码重用性:面向对象的编程也是封装数据和保持组件在功能上彼此分离的好方法。 如果为一个程序创建链接列表类,那么只要链接列表类是自包含的,就可以轻松地在另一个程序中重用此代码,这意味着它不依赖外部代码来完成它的工作。

什么是对象?

一般来说,我们可以将一个对象看作是具有唯一标识的东西。 这在“现实世界”以及软件世界中都是如此。 例如,自行车是具有唯一身份的物体,因为它在空间和时间上占据独特的位置。 同样,程序中的变量在随机存取存储器中具有唯一的位置和执行时间。 此外,诸如自行车的对象拥有其自己的一组属性和行为。 属性可以包括品牌名称,颜色和价格。 行为可以包括踏板,制动器和换档。

What_Is_Object (14)

在面向对象编程中,类是创建对象的模板。 模板是一组特定的属性和行为。 对象是类的实例。 对象实现类属性作为数据和类行为作为函数。 基本上,一个类是一个数据类型,一个对象是该类的一个变量。

类函数(即方法)

类的函数称为方法。 下面是主要的方法类型:

构造函数和析构函数

一般来说,对象有两个基本方法:构造函数和析构函数。 构造函数是实例化对象并根据需要分配动态内存。 接受参数的构造函数称为正常构造函数,而不构造函数称为默认构造函数。 接受对类的另一个实例的引用的构造函数称为复制构造函数。 析构函数用于释放由对象使用的任何动态内存。 析构函数在对象的生命周期结束时或程序终止时调用。

OOP_Methods (4)

Setters和Getters

除了构造函数和析构函数,对象还有另外两种方法:setter和getter。 setter是一种改变对象的数据属性的方法。 例如,setPrice将以浮点数作为参数,并将price变量设置为传入的值。getter方法检索对象的数据。 吸气剂不会改变对象,而是让你窥视它。

OOP_Methods (13)

访问说明符

在C ++中,有一些关键字用于控制数据成员和类的方法的访问级别:

  • 私有意味着类成员只对类本身可见。 通常,数据成员是私有的,因此您只能通过setter和getter方法访问它们。 (注意:默认情况下,类成员在C ++中被视为private)。
  • 保护意味着类成员只能对类及其派生类可见。 保护用于继承链。 (我们将在下一个面向对象编程系列教程中介绍继承。
  • 公共意味着类成员对类外的实体可见。 通常,大多数类方法是public的,因此可以从类外部调用它们。

OOP_PPP (4)

保持一些类属性私有和独立于其他代码的过程是封装。 封装是面向对象编程的一个关键方面。 它保持代码容易维护,保持它自包含。 它还通过将数据仅限于需要的地方来实现更大的应用程序安全性。

编码示例

以下是制作工作程序示例所需的一切。 只需将您需要的代码复制并粘贴到您自己的项目文件中,或从Github链接下载项目文件。


为了简单起见,您可以在main.cpp中声明和定义Bike类。 首先,在Bike.h中将#define Bike_h和#endif之间的所有内容复制并粘贴到主函数外的main.cpp中。 接下来,将Bike.cpp中的所有内容复制并粘贴到main.cpp主函数外部。 对于开始,将类声明,定义和实现合并到一个文件是快速和肮脏的。 然而,从长远来看,最好将类定义和声明封装在远离main.cpp的独立文件中。

Bike_Class

Bike.h

//*****************************************************************//  Bike.h//  Objects_Project////  Created by Karlina Beringer on July 8, 2014.////  This header file contains the Bike class declaration.//  Bike objects model bicycles in the real world.//*****************************************************************#ifndef Bike_h#define Bike_h#include <iostream>#include <string>#include <iomanip>using namespace std;class Bike{//-----------------------------------------------------------------// Bike attributes (class members are private by default)//-----------------------------------------------------------------private:    string brand;    string model;    double price;    double speed;//-----------------------------------------------------------------// Bike behaviors (a.k.a. methods)//-----------------------------------------------------------------public:    // Default constructor creates a generic Bike object.    Bike();        // Normal construcor creates a custom Bike object.    Bike( string brand, string model, double price, double speed );    // Copy constructor creates Bike object clone.    Bike( Bike & object );        // Getter returns the brand of the bike object.    string getBrand();        // Getter returns the model of the Bike object.    string getModel();        // Getter returns the price of the Bike object.    double getPrice();        // Getter returns the speed in mph of the Bike object.    double getSpeed();        // Getter computes the distance covered by the Bike.    double getDistance( double minutes );        // Getter prints a summary of the Bike object's state.    void print();        // Setter changes the brand of the Bike object.    void setBrand( string brand );        // Setter changes the model of the Bike object.    void setModel( string model );        // Setter changes the price of the Bike object.    void setPrice( double price );        // Setter changes the speed of the Bike object.    void setSpeed( double speed );        // Destructor is called when the program terminates.    ~Bike();};#endif//*****************************************************************// End of File//*****************************************************************

Bike.cpp

//*****************************************************************//  Bike.cpp//  Objects_Project////  Created by Karlina Beringer on July 8, 2014.////  This source file contains the Bike class definition.//  Bike objects model bicycles in the real world.//*****************************************************************#include "Bike.h"// Default constructor creates a generic Bike object.// The double colons are called the "resolution specifier."Bike::Bike(){    brand = "brand";    model = "model";    price = 0.0;    speed = 0.0;}// Normal constructor creates a generic Bike object.// Keyword "this" points to the instance calling the method.Bike::Bike( string brand, string model, double price, double speed ){    this -> brand = brand;    this -> model = model;    this -> price = price;    this -> speed = speed;}// Copy constructor creates Bike object clone.// The "dot operator" returns an attribute of the object.Bike::Bike( Bike & object ){    this -> brand = object.brand;    this -> model = object.model;    this -> price = object.price;    this -> speed = object.speed;}// Getter returns the brand of the Bike object.string Bike::getBrand(){    return brand;}// Getter returns the model of the Bike object.string Bike::getModel(){    return model;}// Getter returns the price of the Bike object.double Bike::getPrice(){    return price;}// Getter returns the speed in mph of the Bike object.double Bike::getSpeed() {    return speed;}// Getter computer the distance covered by the Bike.// Distance = Speed * Time// Miles = (Miles/Hour)*(Minutes)*(Hour/60 Minutes)double Bike::getDistance( double minutes ){    return speed * (minutes/60);}// Getter prints a summary of the Bike object's state.void Bike::print(){    cout << "nnBrand:t" << brand << endl;    cout << "Model:t" << model << endl;    cout << "Price:t$" << setprecision(2) << fixed << price << endl;    cout << "Speed:t" << setprecision(4) << speed << " miles per hour" << endl;}// Setter changes the brand of the Bike object.void Bike::setBrand( string brand ) {    this -> brand = brand;}// Setter changes the model of the Bike object.void Bike::setModel( string model ){    this -> model = model;}// Setter changes the price of the Bike object.void Bike::setPrice( double price ){    this -> price = price;}// Setter changes the speed of the Bike object.void Bike::setSpeed( double speed ){    this -> speed = speed;}// Destructor is called when the program terminates.Bike::~Bike(){    cout << "Deleting Bike object..." << endl;}//*****************************************************************// End of File//*****************************************************************

main.cpp

//*****************************************************************//  main.cpp//  Objects_Project////  Created by Karlina Beringer on July 8, 2014.////  This file contains the main function of the program.//  Main implements objects of the Bike class.//  Bike objects model bicycles in the real world.//*****************************************************************// Include the header file for the Bike class.#include "Bike.h"int main(){    cout << "Starting program...nn";        // Create two Bike objects.    // Bike is a data type. A and B are Bike variables.    // A uses the default constructor.    // B uses the normal constructor.    cout << "Creating Bike objects A and B...n";    Bike A;    Bike B( "Magna", "Glacier Point", 120, 5 );        // Display contents of each Bike objects.    cout << "Displaying contents of Bike object A...n";    A.print();    cout << "Displaying contents of Bike object B...n";    B.print();        // Set the speed of A to 10 miles per hour.    cout << "nSetting the speed of A to 10 mph...n";    A.setSpeed( 10 );    cout << "Bike A now travels at " << A.getSpeed() << " mph.n";        // Show how far A travels in 15 minutes.    cout << "In 15 minutes, Bike A travels ";    cout << A.getDistance( 15 ) << " miles.nn";        // Create a copy of Bike object B name C.    cout << "Create a copy of Bike object B named C...n";    Bike C( B );    cout << "Displaying contents of copy of C...";    C.print();        // Terminate program.    cout << "nEnding program...n";    return 0;}//*****************************************************************// End of File//*****************************************************************

Program_Output.txt

Starting program...Creating Bike objects A and B...Displaying contents of Bike object A...Brand:brandModel:modelPrice:$0.00Speed:0.0000 miles per hourDisplaying contents of Bike object B...Brand:MagnaModel:Glacier PointPrice:$120.00Speed:5.0000 miles per hourSetting the speed of A to 10 mph...Bike A now travels at 10.0000 mph.In 15 minutes, Bike A travels 2.5000 miles.Displaying contents of copy of C...Brand:MagnaModel:Glacier PointPrice:$120.00Speed:5.0000 miles per hourEnding program...Deleting Bike object...Deleting Bike object...Deleting Bike object...Program ended with exit code: 0
 扩展

面向对象编程概念

如果以前从未使用过面向对象的编程语言,在开始编写任何代码之前,您需要学习一些基本概念。 本课将向您介绍对象,类,继承,接口和包。 每个讨论集中在这些概念如何与真实世界相关,同时提供Java编程语言的语法介绍。

什么是对象?

对象是相关状态和行为的软件包。 软件对象通常用于模拟在日常生活中发现的真实世界对象。 本课解释如何在对象中表示状态和行为,介绍数据封装的概念,并解释以此方式设计软件的好处。

什么是类?

类是创建对象的蓝图或原型。这个部分定义了一个模型化真实世界对象的状态和行为的类。它有意地专注于基础,显示一个简单的类如何干净地建模状态和行为。

什么是继承?

继承提供了一个强大和自然的机制来组织和组织您的软件。本节介绍类如何从其超类继承状态和行为,并解释如何使用Java编程语言提供的简单语法从另一个类派生一个类。

什么是接口?

接口是类和外部世界之间的契约。当一个类实现一个接口时,它承诺提供由该接口发布的行为。本节定义一个简单的接口,并解释实现它的任何类的必要的更改。

什么是包裹?

包是以逻辑方式组织类和接口的命名空间。将代码放入包中使得大型软件项目更容易管理。本节解释为什么这是有用的,并介绍由Java平台提供的应用程序编程接口(API)。





0 0