中级篇 · 1.6 · 中级
类与对象基础
从结构体到类:面向对象的第一步
类(class)= 数据(成员变量)+ 操作(成员函数);对象是类的实例(用类造出来的具体变量)。类把数据和操作绑在一起,外界只能通过公开接口访问数据——这就是封装。
访问限定符
| 限定符 | 类内 | 派生类 | 类外 |
|---|---|---|---|
public | 可访问 | 可访问 | 可访问 |
protected | 可访问 | 可访问 | 不可 |
private | 可访问 | 不可(友元除外) | 不可 |
类的标准骨架
class Student { private: 成员变量; public: set/get 函数, show(); };
- 成员变量全部 private(数据保护),对外暴露 public 的 setter/getter
- setter 里可以写合法性检查(年龄不能为负)——封装的核心价值
- 成员函数可在类内定义(自动内联),也可类内声明、类外用
类名::函数名定义 - 类定义结尾必须有分号
this 指针
每个成员函数都隐含一个 this 指针,指向当前调用该函数的对象。用途:① 参数与成员重名时用 this->x = x; 区分;② return *this 返回对象自身,实现链式调用。
对象数组
Student cls[3]; 一次造 3 个对象,cls[i].show() 逐个调用——管理批量的标配。
设计类的思路是「先想接口,再想数据」:先列出对象该会做什么(public 成员函数),再决定内部存什么(private 成员变量),getter/setter 按 getXxx / setXxx 命名。考题中「以下哪个成员能在类外访问」几乎必考,答案只取决于它是 public 还是 private,与对象是谁无关。
void Student::show());④ this 指针的概念题。避坑指南
类定义结尾漏分号
错误写法
class Student {
public:
void show() { /* ... */ }
private:
int age;
} // 缺分号!
int main() { ... } // 编译器把 main 当变量声明,报错满屏正确写法
class Student {
public:
void show() { /* ... */ }
private:
int age;
}; // 类定义以分号结束
int main() { ... }和 struct 一样,类定义是类型声明,必须分号结尾。漏写后的报错信息往往指向「下一行」,极具迷惑性。
类外直接访问 private 成员
错误写法
class Student {
private:
int age; // 私有
public:
void show() { std::cout << age; }
};
int main() {
Student s;
s.age = 20; // 编译错误:age 是 private,类外不可访问
}正确写法
class Student {
private:
int age;
public:
void setAge(int a) { // 通过公有接口
if (a >= 0 && a <= 150) age = a; // 顺手做合法性检查
}
int getAge() { return age; }
};
int main() {
Student s;
s.setAge(20);
std::cout << s.getAge() << std::endl;
}private 成员只有类内(和友元)能碰。类外想读写,必须走 public 的 setter/getter——这不是麻烦,而是封装带来的「数据进出都要过安检」。
类外定义成员函数忘写类名::
错误写法
class Rect {
public:
double area(); // 只是声明
private:
double w = 3, h = 4;
};
double area() { // 错!这是全局函数,不是 Rect 的成员
return w * h; // 而且访问不到私有成员 w、h
}正确写法
class Rect {
public:
double area(); // 类内声明
private:
double w = 3, h = 4;
};
double Rect::area() { // 类外定义:必须 类名::
return w * h;
}返回类型 类名::函数名(参数) 才是「类外定义成员函数」。少了 Rect:: 就成了普通全局函数,既访问不到私有成员,也不会被对象调用到。
代码实践
Student 类:封装与 getter/setter
私有数据 + 公有接口的标准封装范本:
student_class.cpp
#include <iostream>
#include <string>
using namespace std;
class Student {
private: // 私有:类外不能直接访问
string name;
int age;
double score;
public: // 公有:对外接口
void setInfo(string n, int a, double s) {
name = n;
age = a;
score = s;
}
string getName() { return name; }
double getScore() { return score; }
void show() {
cout << name << " " << age << " 岁, 成绩 " << score << endl;
}
};
int main() {
Student s;
s.setInfo("小明", 19, 92.5);
s.show();
cout << "通过接口读取: " << s.getName() << endl;
Student cls[2]; // 对象数组
cls[0].setInfo("小红", 18, 88.0);
cls[1].setInfo("小刚", 20, 76.5);
double sum = cls[0].getScore() + cls[1].getScore();
cout << "两人平均分: " << sum / 2 << endl;
return 0;
}预期输出
小明 19 岁, 成绩 92.5
通过接口读取: 小明
两人平均分: 82.25- 数据 private、接口 public 是封装的标准布局
- 类内定义的成员函数自动倾向内联,短函数直接写在类里最方便
- 对象数组每个元素都是完整对象,逐个调用成员函数即可
this 指针与链式调用
用 return *this 让成员函数可以像链条一样连着写:
this_chain.cpp
#include <iostream>
using namespace std;
class Counter {
private:
int value;
public:
Counter() : value(0) {}
Counter &add(int n) { // 返回自身引用 → 支持链式
value += n;
return *this; // this 指向当前对象
}
Counter &sub(int n) {
value -= n;
return *this;
}
void show(string tag) {
cout << tag << " value = " << value << endl;
}
};
int main() {
Counter c;
c.show("初始");
c.add(10);
c.show("加 10 后");
c.add(5).sub(3).add(2); // 链式调用
c.show("链式后");
return 0;
}预期输出
初始 value = 0
加 10 后 value = 10
链式后 value = 14this是成员函数的隐藏参数,指向「. 左边那个对象」return *this返回自己,于是c.add(5)的结果还是 c,可以继续.sub(3)- 链式算式:0 +10 → 10,+5 -3 +2 → 14
类外定义成员函数与数据校验
声明在类内、定义在类外的规范写法,顺带展示封装的校验价值:
rect_class.cpp
#include <iostream>
using namespace std;
class Rect {
private:
double width;
double height;
public:
void setSize(double w, double h); // 类内声明
double area();
double getWidth();
};
// 类外定义:必须用 类名:: 限定
void Rect::setSize(double w, double h) {
if (w > 0 && h > 0) { // 封装带来的数据校验
width = w;
height = h;
} else {
width = height = 1; // 非法数据给默认值
}
}
double Rect::area() { return width * height; }
double Rect::getWidth() { return width; }
int main() {
Rect r;
r.setSize(3.0, 4.0);
cout << "宽 = " << r.getWidth() << endl;
cout << "面积 = " << r.area() << endl;
r.setSize(-5, 10); // 非法数据被拦截
cout << "非法输入后宽 = " << r.getWidth() << endl;
return 0;
}预期输出
宽 = 3
面积 = 12
非法输入后宽 = 1- 类外定义的每一处都带
Rect::,漏了就变全局函数 - setter 是数据的唯一入口,校验写在这里一次管所有调用方
- -5 被「安检」拦下,宽回落到默认值 1——这就是私有成员的意义
巩固练习
Circle 类求面积 · 简单
提示
参考解答
#include <iostream>
using namespace std;
class Circle {
private:
double radius;
public:
void setR(double r) { radius = r; }
double area() { return 3.14159 * radius * radius; }
};
int main() {
Circle c;
c.setR(2.5);
cout << "面积: " << c.area() << endl;
return 0;
}预期输出
面积: 19.6349访问权限判断题 · 简单
① 类内函数访问本类 private 成员
② main 中
obj.privateVar = 5;③ main 中调用 public 成员函数
④ 类内函数访问 public 成员
参考程序演示了合法的情形,非法的那行已注释掉。
提示
参考解答
#include <iostream>
using namespace std;
class Demo {
private:
int secret = 1;
public:
int open = 2;
void touch() { secret += open; } // ①④ 合法:类内随便访问
};
int main() {
Demo d;
d.open = 5; // ③ 合法:public 处处可访问
d.touch();
// d.secret = 9; // ② 编译错误:类外不能访问 private
cout << "只有 ② 会编译错误" << endl;
return 0;
}预期输出
只有 ② 会编译错误Book 类与 getter/setter · 中等
{"C++基础", 39.9} 输出,再故意设 -10 验证拦截。提示
if (p < 0) p = 0;。参考解答
#include <iostream>
#include <string>
using namespace std;
class Book {
private:
string title;
double price;
public:
void set(string t, double p) {
title = t;
price = (p < 0) ? 0 : p;
}
string getTitle() { return title; }
double getPrice() { return price; }
};
int main() {
Book b;
b.set("C++基础", 39.9);
cout << b.getTitle() << " " << b.getPrice() << endl;
b.set("盗版书", -10);
cout << b.getTitle() << " " << b.getPrice() << endl;
return 0;
}预期输出
C++基础 39.9
盗版书 0类外定义成员函数 · 中等
inc()、get()、reset() 三个成员函数全部在类外用 Counter:: 定义。inc 后输出计数值。提示
void Counter::inc() { count++; }。参考解答
#include <iostream>
using namespace std;
class Counter {
private:
int count;
public:
Counter() : count(0) {}
void inc();
int get();
void reset();
};
void Counter::inc() { count++; }
int Counter::get() { return count; }
void Counter::reset() { count = 0; }
int main() {
Counter c;
c.inc();
c.inc();
c.inc();
cout << "计数: " << c.get() << endl;
c.reset();
cout << "重置后: " << c.get() << endl;
return 0;
}预期输出
计数: 3
重置后: 0对象数组统计最高分学生 · 困难
{李四 76, 张三 88, 王五 95},找出并输出最高分学生的姓名与成绩。提示
参考解答
#include <iostream>
#include <string>
using namespace std;
class Student {
private:
string name;
double score;
public:
void setInfo(string n, double s) { name = n; score = s; }
string getName() { return name; }
double getScore() { return score; }
};
int main() {
Student cls[3];
cls[0].setInfo("李四", 76);
cls[1].setInfo("张三", 88);
cls[2].setInfo("王五", 95);
int best = 0;
for (int i = 1; i < 3; i++) {
if (cls[i].getScore() > cls[best].getScore()) best = i;
}
cout << "最高分: " << cls[best].getName() << " "
<< cls[best].getScore() << endl;
return 0;
}预期输出
最高分: 王五 95延伸阅读
菜鸟教程 C++ 类 & 对象
类定义、成员函数与访问修饰符
cppreference 类声明
类语法、访问控制与 this 的权威文档
Wandbox
在线验证类的封装与成员访问