C++面向对象编程入门指南。

C++类和对象基础概念

C++是一种面向对象的编程语言,类和对象是其核心特性。类是一种用户自定义的数据类型,用于封装数据和行为。对象是类的实例,通过对象可以访问类中定义的成员变量和成员函数。

类的基本语法如下:

class ClassName {
    // 访问修饰符(public、private、protected)
    public:
        // 成员变量
        int memberVar;
        
        // 成员函数
        void memberFunc() {
            // 函数实现
        }
};

类的成员变量和成员函数

成员变量用于存储对象的状态,成员函数用于定义对象的行为。访问修饰符控制成员的可见性:

  • public:成员可以在类外部访问。
  • private:成员只能在类内部访问。
  • protected:成员可以在类及其派生类中访问。

示例代码:

#include <iostream>
using namespace std;

class Rectangle {
    private:
        int width, height;
    
    public:
        void setDimensions(int w, int h) {
            width = w;
            height = h;
        }
        
        int getArea() {
            return width * height;
        }
};

int main() {
    Rectangle rect;
    rect.setDimensions(5, 10);
    cout << "Area: " << rect.getArea() << endl;
    return 0;
}

构造函数和析构函数

构造函数用于初始化对象,析构函数用于清理资源。构造函数与类同名,析构函数名前加~

示例代码:

#include <iostream>
using namespace std;

class Student {
    private:
        string name;
        int age;
    
    public:
        // 构造函数
        Student(string n, int a) {
            name = n;
            age = a;
            cout << "Student created: " << name << endl;
        }
        
        // 析构函数
        ~Student() {
            cout << "Student destroyed: " << name << endl;
        }
        
        void display() {
            cout << "Name: " << name << ", Age: " << age << endl;
        }
};

int main() {
    Student s1("Alice", 20);
    s1.display();
    return
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值