跳到内容

this指针与const成员 ​

什么是 this 指针 ​

每个对象都有自己的一份数据成员,但成员函数的代码是共享的——同一个函数被不同对象调用时,它怎么知道操作的是哪个对象的数据?答案是 this 指针。

this 是一个隐式指针,指向调用该成员函数的那个对象。在成员函数内部,访问成员名时编译器会自动加上 this-> 前缀。你也可以显式写出来。

cpp
// box.h
#ifndef BOX_H_
#define BOX_H_

class Box
{
private:
    double width;
    double height;
    double depth;
public:
    Box(double w, double h, double d);
    double volume() const;
    const Box& largerThan(const Box& other) const;  // 返回较大者
    void show() const;
};

#endif
cpp
// box.cpp
#include <iostream>
#include "box.h"

Box::Box(double w, double h, double d)
    : width(w), height(h), depth(d)
{
}

double Box::volume() const
{
    // 下面三种写法等价:
    return width * height * depth;          // 隐式
    // return this->width * this->height * this->depth;  // 显式
    // return (*this).width * (*this).height * (*this).depth;
}

void Box::show() const
{
    std::cout << "宽" << width << " 高" << height
              << " 深" << depth << " 体积" << volume() << "\n";
}

width 在成员函数里其实就是 this->width。this 由编译器悄悄传进来,你通常不需要显式写它。

用 this 返回对象自身 ​

this 最常见的用途是返回调用者对象本身,从而支持链式调用或比较操作。下面这个方法比较两个盒子,返回较大那个的引用:

cpp
const Box& Box::largerThan(const Box& other) const
{
    if (other.volume() > this->volume())
        return other;       // 参数更大,返回它
    else
        return *this;       // 否则返回自己(解引用 this 得到对象本身)
}

关键点:

  • *this 是"当前对象本身"。返回引用时用 return *this;。
  • 函数返回 const Box&,避免拷贝大对象,也防止返回值被随意修改。
  • 参数也用 const Box&,既避免拷贝又保证不被改。

使用:

cpp
#include <iostream>
#include "box.h"

int main()
{
    Box a(2, 3, 4);
    Box b(1, 5, 6);
    std::cout << "a 体积 = " << a.volume() << "\n";
    std::cout << "b 体积 = " << b.volume() << "\n";
    const Box& big = a.largerThan(b);
    std::cout << "较大者: ";
    big.show();
    return 0;
}

注意 largerThan 返回的是引用,所以 big 绑定到原始对象 a 或 b,没有发生拷贝。如果返回类型改成 Box(按值返回),就会拷贝一份新对象,开销更大。

const 成员函数 ​

看上面每个方法声明后面都跟着的 const:

cpp
double volume() const;
void show() const;
const Box& largerThan(const Box& other) const;

这个 const 放在参数列表之后,表示这个函数不会修改对象的数据成员。它是"承诺只读"的标记:

  • 编译器会检查函数体内是否真的没改成员,改了就报错。
  • const 对象只能调用 const 成员函数(否则编译器无法保证它不被改)。
  • 非 const 对象既能调 const、也能调非 const 成员函数。
cpp
const Box fixed(1, 1, 1);
fixed.volume();       // OK:volume 是 const 成员函数
fixed.show();         // OK:show 是 const 成员函数
// fixed.largerThan(fixed);  // OK:largerThan 也是 const
// 如果有个非 const 的 setWidth(),fixed.setWidth(2) 就会编译报错

养成习惯:不修改对象的成员函数,一律加 const。这叫 const 正确性(const-correctness)。它不仅让编译器帮你查错,还让 const 对象能用上你的类。

const 与重载 ​

const 修饰成员函数也参与重载:同名同参数、一个有 const 一个没有,是两个不同的函数。常用于按 const 与否提供不同版本的访问器:

cpp
class Buffer
{
    char* data;
    int size;
public:
    Buffer(int n);
    ~Buffer();
    char& at(int i);            // 非 const 版本:可读写
    char& at(int i) const;     // const 版本:只读(但仍返回引用)
};

Buffer::Buffer(int n) : size(n) { data = new char[n]; }
Buffer::~Buffer() { delete[] data; }

char& Buffer::at(int i) { return data[i]; }
char& Buffer::at(int i) const { return data[i]; }
cpp
Buffer wb(16);
const Buffer rb(16);
wb.at(0) = 'A';      // 调非 const 版,可写
char c = rb.at(0);   // 调 const 版,对 const 对象仍可读

(严格说上面 const 版返回 char& 让人能间接改内容,更好的做法是返回 const char&。这里只为说明重载机制。)

this 的类型 ​

this 的类型是 类名* const(指向本类的常量指针)——指针本身不能改(不能 this = ...),但指向的对象在非 const 成员函数里是可以改的。在 const 成员函数里,this 的类型是 const 类名* const,所以你不能通过它改成员。

课后练习 ​

  1. 加 largerThan:给之前的 Lamp 类加一个 const Lamp& brighterThan(const Lamp& other) const 方法,比较亮度并返回较亮那个的引用。在 main 里用三个 Lamp 连续比较找出最亮的。
  2. const 正确性:把 Lamp 类中所有不该修改对象的方法都加上 const。然后写一个 const Lamp night;,尝试调用各方法,确认只有 const 方法能被调用、写方法被编译器挡住。
  3. 显式 this:写一个类,在某个成员函数里显式用 this->成员 访问所有数据成员,体会它和省略 this-> 的等价关系。
  4. 返回引用防拷贝:写一个含 std::string 成员的类,提供一个 const Foo& pick(const Foo& other) const 方法返回两者之一。在调用处打印返回对象的地址和原始对象地址,确认引用绑定(地址相同)而非拷贝。