主题
对象数组与类作用域
对象数组
类一旦定义好,就可以像 int、double 那样声明数组。每个元素都是一个独立的对象,各有自己的数据:
cpp
// lamp2.h
#ifndef LAMP2_H_
#define LAMP2_H_
#include <string>
class Lamp
{
private:
std::string room;
int brightness;
public:
Lamp(); // 默认构造
Lamp(const std::string& r, int b); // 带参构造
void dim(int delta);
void show() const;
const std::string& where() const { return room; }
int level() const { return brightness; }
};
#endif声明对象数组时,如果不给初值,每个元素都会调用默认构造函数:
cpp
Lamp corridor[4]; // 4 个 Lamp,都走默认构造用构造函数初始化对象数组
如果想给每个元素指定初值,可以用初始化列表,每个元素调用一次对应构造函数:
cpp
#include <iostream>
#include "lamp2.h"
int main()
{
Lamp rooms[3] = {
Lamp("客厅", 80),
Lamp("卧室", 30),
Lamp("书房", 60)
};
for (int i = 0; i < 3; ++i)
rooms[i].show();
// 找出最亮的那个
int idx = 0;
for (int i = 1; i < 3; ++i)
if (rooms[i].level() > rooms[idx].level())
idx = i;
std::cout << "最亮的是: " << rooms[idx].where() << "\n";
return 0;
}如果初始化列表的元素少于数组长度,剩余元素用默认构造补齐;如果多于数组长度则编译报错。也可以部分给初值、部分留空:
cpp
Lamp mix[4] = { Lamp("厨房", 50), Lamp("阳台", 20) };
// mix[2]、mix[3] 走默认构造类作用域
类本身定义了一个作用域。类里声明的成员名(数据成员、成员函数、嵌套类型、枚举)都在类作用域内,外部使用时要加 类名:: 限定。
这意味着:
- 类内成员函数之间互相引用成员名,不用加前缀。
- 类外定义成员函数、或访问静态成员、嵌套类型时,要用
类名::说明它属于哪个类。
cpp
// counter.h —— 含嵌套类型和常量的类
#ifndef COUNTER_H_
#define COUNTER_H_
class Counter
{
public:
typedef int CountType; // 嵌套类型,类作用域内
enum { CAPACITY = 8 }; // 类作用域内的常量
private:
CountType items[CAPACITY]; // 用到自己的嵌套类型和常量
int used;
public:
Counter();
bool push(CountType v);
bool pop(CountType& v);
bool isEmpty() const;
bool isFull() const;
int count() const;
};
#endifcpp
// counter.cpp
#include "counter.h"
Counter::Counter() : used(0)
{
}
bool Counter::push(CountType v)
{
if (used >= CAPACITY)
return false;
items[used++] = v;
return true;
}
bool Counter::pop(CountType& v)
{
if (used == 0)
return false;
v = items[--used];
return true;
}
bool Counter::isEmpty() const { return used == 0; }
bool Counter::isFull() const { return used == CAPACITY; }
int Counter::count() const { return used; }类外定义成员函数时,参数和返回类型中用到的 CountType、CAPACITY 都要带 Counter:: 前缀(因为此时编译器还不在 Counter 作用域里,进入函数体后才进入)。上面的 bool Counter::push(CountType v) 里 CountType 之所以能简写,是因为 Counter::push 这个限定名让编译器进入了 Counter 作用域——更保险的写法是 Counter::CountType。
类作用域里的常量
类里常需要一些"类相关的常量",比如上面的 CAPACITY。几种做法:
enum { CAPACITY = 8 };:旧式枚举常量,不占存储、可在类内直接给出初值,是最传统的做法。static const int CAPACITY = 8;:静态常量整型,C++17 之前在类内只是声明,定义要放类外;C++98/03 常用enum绕开这个限制。static constexpr int CAPACITY = 8;:C++11 起推荐,既是真正的常量表达式又能在类内直接给值,还能用于数组大小等需要常量表达式的场合。
cpp
class Counter
{
static constexpr int CAPACITY = 8; // C++11+,推荐
int items[CAPACITY];
// ...
};作用域分辨与查找
理解成员函数体内名字查找的过程:
- 先在函数局部找。
- 再在所在类的成员里找。
- 再在外层作用域(命名空间、全局)找。
所以成员函数里写 used 能找到本类的 used 成员;如果有个全局变量也叫 used,想用它就得写 ::used。
抽象数据类型:栈示例
把封装、构造、作用域综合起来,可以实现一个栈这种抽象数据类型。栈的特点是后进先出(LIFO):
cpp
// todoStack.h —— 用类实现一个待办栈
#ifndef TODOSTACK_H_
#define TODOSTACK_H_
class TodoStack
{
public:
using Item = int; // C++11 类型别名,类作用域内
static constexpr int MAX = 10;
private:
Item data[MAX];
int top;
public:
TodoStack();
bool isEmpty() const;
bool isFull() const;
bool push(const Item& v); // 压栈
bool pop(Item& v); // 出栈
};
#endifcpp
// todoStack.cpp
#include "todostack.h"
TodoStack::TodoStack() : top(0) {}
bool TodoStack::isEmpty() const { return top == 0; }
bool TodoStack::isFull() const { return top == MAX; }
bool TodoStack::push(const Item& v)
{
if (top >= MAX)
return false;
data[top++] = v;
return true;
}
bool TodoStack::pop(Item& v)
{
if (top <= 0)
return false;
v = data[--top];
return true;
}使用:
cpp
#include <iostream>
#include "todostack.h"
int main()
{
TodoStack s;
for (int i = 1; i <= 3; ++i)
s.push(i * 10);
int x;
while (s.pop(x))
std::cout << x << " "; // 30 20 10,后进先出
std::cout << "\n";
return 0;
}这里 TodoStack 把内部数组 data 和下标 top 藏在 private 里,外部只能通过 push/pop 操作——这就是用类封装一个抽象数据类型的标准做法。
课后练习
- 对象数组初始化:写一个
Book类(书名、页数),构造函数支持默认和带参两种。声明一个长度为 4 的Book数组,前两个用带参构造初始化、后两个默认构造,然后逐个打印信息。 - 嵌套类型与常量:给上面的
TodoStack加一个嵌套类型enum Mode { LIFO, FIFO };,再写一个static constexpr int MAX = 16;。在类外定义成员函数时,尝试用TodoStack::MAX、TodoStack::Mode访问它们,体会类作用域限定。 - 栈的扩展:给
TodoStack加一个peek(Item& v) const方法,返回栈顶元素但不弹出。注意它该不该是const成员函数。 - 常量选择:把
TodoStack里的static constexpr int MAX分别改写成enum { MAX = 10 };和static const int MAX = 10;两种形式,各编译一次,观察 C++17 下哪种能在类内直接给初值且可用于数组大小声明。