一、”类” 的介绍
对象:对象是对现实世界中的事物或概念的抽象表示。在C++中,对象是由类创建的实体。对象包含数据(属性或成员变量)和对这些数据进行操作的方法(成员函数)。
实例:实例是类的具体对象。当你使用类的构造函数创建一个对象时,你就创建了一个类的实例。每个实例都有其自己的数据成员(即属性)和可以调用其成员函数(即方法)。
属性:属性是对象的特性或状态,它们存储对象的数据。在C++中,这些通常被称为成员变量或数据成员。
方法:方法是对象可以执行的操作或行为。在C++中,这些被称为成员函数。它们通常用于修改对象的属性或基于对象的属性执行某些计算
1 2 3 4 5 6 7 8 9 10 11 12
| 1. 类的声明
class 类名称 { public: 公有成员(外部接口) private: 私有成员 (只允许本类中的函数访问,而类外部的任何函数都不能访问) protected: 保护成员(与private类似,差别表现在继承与派生时) };
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| #include <iostream> using namespace std; class Test { public: int x_; void init(int x, int y,int z); void display() { cout<< x_ << endl; }; private: int y_; protected: int z_; }; void Test::init(int x, int y, int z) { x_ = x; y_ = y; z_ = z; } int main() { Test t; t.init(1,2,3); t.display(); return 0; }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| class Car { private: std::string color; std::string make; std::string model; int year; public: Car(std::string c, std::string m, std::string mod, int y) : color(c), make(m), model(mod), year(y) {} void start() { } void stop() { } }; int main() { Car myCar("Red", "Toyota", "Corolla", 2020); myCar.start(); myCar.stop(); return 0; }
|