第一节 · 系统的构造 · 类的定义与封装
struct Student
{
string name;
int age;
int score;
};
Student s;
s.name = "Alice";
s.age = 18;
s.score = 95;习题
Last updated
struct Student
{
string name;
int age;
int score;
};
Student s;
s.name = "Alice";
s.age = 18;
s.score = 95;Last updated
class Student
{
private:
string name;
int age;
int score;
public:
void setName(const string& n)
{
name = n;
}
string getName() const
{
return name;
}
void setScore(int s)
{
if (s >= 0 && s <= 100)
score = s;
}
int getScore() const
{
return score;
}
};class Example
{
private:
int privateVar; // 只有类内部可以访问
protected:
int protectedVar; // 类内部和派生类可以访问
public:
int publicVar; // 任何地方都可以访问
void publicFunc() // 公有成员函数
{
privateVar = 10; // 在类内部,可以访问私有成员
}
};
int main()
{
Example e;
e.publicVar = 1; // OK,公有成员
// e.privateVar = 2; // 错误!私有成员不能在类外访问
e.publicFunc(); // OK
return 0;
}class MyClass
{
int x; // 默认是 private
};
struct MyStruct
{
int x; // 默认是 public
};// 没有封装
struct BankAccount
{
double balance;
};
BankAccount account;
account.balance = -1000; // 直接设置为负数,不合理!
// 有封装
class BankAccount
{
private:
double balance;
public:
BankAccount() : balance(0) {}
void deposit(double amount)
{
if (amount > 0)
balance += amount;
}
bool withdraw(double amount)
{
if (amount > 0 && amount <= balance)
{
balance -= amount;
return true;
}
return false;
}
double getBalance() const
{
return balance;
}
};
BankAccount account;
account.deposit(1000); // OK
account.withdraw(500); // OK
// account.balance = -1000; // 错误!不能直接访问class Rectangle
{
private:
double width;
double height;
public:
// 设置尺寸
void setSize(double w, double h)
{
width = w;
height = h;
}
// 计算面积
double area() const
{
return width * height;
}
// 计算周长
double perimeter() const
{
return 2 * (width + height);
}
};
int main()
{
Rectangle rect;
rect.setSize(5, 3);
cout << "面积: " << rect.area() << endl; // 15
cout << "周长: " << rect.perimeter() << endl; // 16
return 0;
}class Rectangle
{
private:
double width;
double height;
public:
void setSize(double w, double h); // 声明
double area() const; // 声明
double perimeter() const; // 声明
};
// 在类外定义,需要使用 类名::函数名 的形式
void Rectangle::setSize(double w, double h)
{
width = w;
height = h;
}
double Rectangle::area() const
{
return width * height;
}
double Rectangle::perimeter() const
{
return 2 * (width + height);
}#include <iostream>
#include <string>
using namespace std;
class Person
{
private:
string name;
int age;
public:
// 设置姓名
void setName(const string& n)
{
if (!n.empty())
name = n;
}
// 获取姓名
string getName() const
{
return name;
}
// 设置年龄
void setAge(int a)
{
if (a >= 0 && a <= 150)
age = a;
}
// 获取年龄
int getAge() const
{
return age;
}
// 自我介绍
void introduce() const
{
cout << "我是 " << name << ",今年 " << age << " 岁。" << endl;
}
};
int main()
{
Person p;
p.setName("张三");
p.setAge(25);
p.introduce(); // 我是 张三,今年 25 岁。
return 0;
}