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
1078

被折叠的 条评论
为什么被折叠?



