00.11_类与结构体
类与结构体
问题描述
类和结构体是面向对象编程的基本单元,用于将数据和操作数据的方法组织在一起。它们提供了一种将相关数据和功能封装的方式。
基本概念
特点
- 数据封装
- 访问控制
- 继承和多态(类)
- 构造和析构
- 成员函数和变量
代码实现
- 结构体
// 基本结构体
struct Point {
int x, y; // 默认public
Point(int x = 0, int y = 0) : x(x), y(y) {} // 构造函数
double distance(const Point& other) {
int dx = x - other.x;
int dy = y - other.y;
return sqrt(dx * dx + dy * dy);
}
};
// 使用结构体
Point p1(3, 4);
Point p2(0, 0);
cout << p1.distance(p2) << endl; // 输出:5
// Java没有结构体,使用类实现
public class Point {
public int x, y; // public成员
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public double distance(Point other) {
int dx = x - other.x;
int dy = y - other.y;
return Math.sqrt(dx * dx + dy * dy);
}
}
// 使用类
Point p1 = new Point(3, 4);
Point p2 = new Point(0, 0);
System.out.println(p1.distance(p2)); // 输出:5.0
# Python使用类实现结构体功能
class Point:
def __init__(self, x: int = 0, y: int = 0):
self.x = x # Python的成员默认public
self.y = y
def distance(self, other: 'Point') -> float:
dx = self.x - other.x
dy = self.y - other.y
return (dx * dx + dy * dy) ** 0.5
# 使用类
p1 = Point(3, 4)
p2 = Point(0, 0)
print(p1.distance(p2)) # 输出:5.0
- 类
class Student {
private:
string name;
int age;
vector<int> scores;
public:
// 构造函数
Student(string n, int a) : name(n), age(a) {}
// 成员函数
void addScore(int score) {
scores.push_back(score);
}
double getAverage() const {
if (scores.empty()) return 0;
int sum = 0;
for (int score : scores) {
sum += score;
}
return static_cast<double>(sum) / scores.size();
}
// getter和setter
string getName() const { return name; }
void setName(string n) { name = n; }
int getAge() const { return age; }
void setAge(int a) { age = a; }
};
// 使用类
Student s("Alice", 20);
s.addScore(85);
s.addScore(90);
cout << s.getName() << "'s average: " << s.getAverage() << endl;
public class Student {
private String name;
private int age;
private ArrayList<Integer> scores;
// 构造函数
public Student(String name, int age) {
this.name = name;
this.age = age;
this.scores = new ArrayList<>();
}
// 成员函数
public void addScore(int score) {
scores.add(score);
}
public double getAverage() {
if (scores.isEmpty()) return 0;
int sum = 0;
for (int score : scores) {
sum += score;
}
return (double)sum / scores.size();
}
// getter和setter
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
}
// 使用类
Student s = new Student("Alice", 20);
s.addScore(85);
s.addScore(90);
System.out.println(s.getName() + "'s average: " + s.getAverage());
class Student:
def __init__(self, name: str, age: int):
self.__name = name # 私有成员
self.__age = age
self.__scores = []
# 成员函数
def add_score(self, score: int) -> None:
self.__scores.append(score)
def get_average(self) -> float:
if not self.__scores:
return 0
return sum(self.__scores) / len(self.__scores)
# 使用property装饰器实现getter和setter
@property
def name(self) -> str:
return self.__name
@name.setter
def name(self, name: str) -> None:
self.__name = name
@property
def age(self) -> int:
return self.__age
@age.setter
def age(self, age: int) -> None:
self.__age = age
# 使用类
s = Student("Alice", 20)
s.add_score(85)
s.add_score(90)
print(f"{s.name}'s average: {s.get_average()}")
应用场景
- 数据抽象
- 对象建模
- 代码组织
- 接口设计
- 数据封装
注意事项
- 访问权限控制
- 内存管理
- 继承关系
- 构造函数设计
- 封装原则
常见示例
- 继承和多态
class Shape {
public:
virtual double area() = 0; // 纯虚函数
virtual ~Shape() {} // 虚析构函数
};
class Circle : public Shape {
private:
double radius;
public:
Circle(double r) : radius(r) {}
double area() override {
return M_PI * radius * radius;
}
};
class Rectangle : public Shape {
private:
double width, height;
public:
Rectangle(double w, double h) : width(w), height(h) {}
double area() override {
return width * height;
}
};
abstract class Shape {
public abstract double area();
}
class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double area() {
return Math.PI * radius * radius;
}
}
class Rectangle extends Shape {
private double width, height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
@Override
public double area() {
return width * height;
}
}
from abc import ABC, abstractmethod
import math
class Shape(ABC):
@abstractmethod
def area(self) -> float:
pass
class Circle(Shape):
def __init__(self, radius: float):
self.__radius = radius
def area(self) -> float:
return math.pi * self.__radius * self.__radius
class Rectangle(Shape):
def __init__(self, width: float, height: float):
self.__width = width
self.__height = height
def area(self) -> float:
return self.__width * self.__height
牛客代码笔记-牛栋 文章被收录于专栏
汗牛充栋,学海无涯。<br/> 内含算法知识点讲解,以及牛客题库精选例题。<br/> 学习算法,从牛栋开始。