跳到内容

结构体与指针参数 ​

结构体把多个相关数据打包成一个整体。把它传给函数有三种方式:按值、按指针、按引用(引用下一章细讲)。本节讲前两种,重点在 const 指针的保护与结构体返回值。

按值传递结构体 ​

结构体可以像普通变量一样按值传递——整个结构体被复制一份给形参。函数内改形参不影响原结构体:

cpp
#include <iostream>

struct Point
{
    double x;
    double y;
};

void shiftCopy(Point p, double dx, double dy)
{
    p.x += dx;
    p.y += dy;
    std::cout << "函数内: (" << p.x << ", " << p.y << ")\n";
}

int main()
{
    Point origin{0.0, 0.0};
    shiftCopy(origin, 3.0, 4.0);
    std::cout << "函数外: (" << origin.x << ", " << origin.y << ")\n";
    return 0;
}

输出:

text
函数内: (3, 4)
函数外: (0, 0)

函数内副本移动了,外面原件没动。按值传递语义安全,但结构体较大时(比如含大数组或字符串)复制开销明显。这时该用指针或引用。

用指针修改原结构体 ​

传指针时,函数拿到的是结构体的地址,通过它直接操作原对象:

cpp
#include <iostream>

struct Point
{
    double x;
    double y;
};

void shift(Point* p, double dx, double dy)
{
    p->x += dx;   // 指针访问成员用 ->,不用 .
    p->y += dy;
}

int main()
{
    Point dot{0.0, 0.0};
    shift(&dot, 3.0, 4.0);          // 取地址传入
    std::cout << "(" << dot.x << ", " << dot.y << ")\n";   // (3, 4)
    return 0;
}

通过指针访问成员要用 -> 运算符(等价于 (*p).x)。调用方需要用 & 取地址。

这里有个隐患:函数可能收到空指针。健壮的写法是检查:

cpp
void shift(Point* p, double dx, double dy)
{
    if (p == nullptr) return;   // 防御空指针
    p->x += dx;
    p->y += dy;
}

用 const 指针表达只读 ​

指针参数既能读又能改,太自由。如果函数只读不改,应当用 const Point* 限定,把"只读"写进签名:

cpp
#include <iostream>
#include <cmath>

struct Point
{
    double x;
    double y;
};

double distanceFromOrigin(const Point* p)
{
    // p->x = 0;  // 编译错误:const 指针不允许修改
    return std::sqrt(p->x * p->x + p->y * p->y);
}

const Point* p 的含义是"指向常量 Point 的指针"——不能通过 p 改对象,但 p 本身可以指向别处。它和 Point* const p(指针本身是常量,不能指向别处,但可改对象)方向相反,别混淆。

传参时遵循"加严可、放宽不可"的规则:把 Point* 传给 const Point* 形参合法(承诺更严),反过来不行。

三种保护层次一览 ​

把指针和 const 的组合列清楚:

写法能改指针指向吗能改所指对象吗
Point* p能能
const Point* p能不能
Point* const p不能能
const Point* const p不能不能

只读参数常用第二种 const Point*。第四种用于"既不改指针也不改对象"的极端情况。

返回结构体 ​

结构体可以按值返回,编译器通常会优化掉多余的拷贝(返回值优化):

cpp
#include <iostream>

struct Point
{
    double x;
    double y;
};

Point makePoint(double x, double y)
{
    Point p{x, y};
    return p;   // 按值返回,安全
}

int main()
{
    Point d = makePoint(3.0, 4.0);
    std::cout << "(" << d.x << ", " << d.y << ")\n";
    return 0;
}

按值返回结构体是最安全的做法——返回的是值的副本,不涉及生命周期问题。也可以返回指针,但同样要保证所指对象存活(指向堆上的、或外部传入的),不能返回指向局部结构体的指针。

结构体数组参数 ​

结构体数组和普通数组一样退化为指针,长度另传:

cpp
#include <iostream>

struct Student
{
    int id;
    int score;
};

// 找最高分学生的下标
int topIndex(const Student arr[], int n)
{
    int best = 0;
    for (int i = 1; i < n; ++i)
        if (arr[i].score > arr[best].score)
            best = i;
    return best;
}

int main()
{
    Student klass[3] = {{1, 78}, {2, 95}, {3, 88}};
    int k = topIndex(klass, 3);
    std::cout << "最高分: 学号 " << klass[k].id
              << " 成绩 " << klass[k].score << "\n";
    return 0;
}

输出:

text
最高分: 学号 2 成绩 95

const Student* 既防止误改,又允许读取每个成员,是结构体数组只读参数的标准写法。

课后练习 ​

  1. 按值 vs 指针:定义一个 struct Circle { double cx, cy, r; };,写两个函数:void growCopy(Circle c, double delta)(按值,改副本)和 void grow(Circle* c, double delta)(指针,改原件)。main 里分别调用,打印前后半径,对比效果。
  2. const 保护:写一个 double area(const Circle* c) 返回圆面积。尝试在函数内写 c->r = 0;,确认编译器报错;然后删掉这行,正常运行。
  3. 结构体返回:写一个 Circle makeCircle(double cx, double cy, double r) 按值返回一个 Circle,在 main 中接收并打印。
  4. 结构体数组:定义 struct Goods { char name[20]; double price; };,写一个 const Goods* cheapest(const Goods arr[], int n),返回指向最便宜商品的指针(只读,故返回 const 指针)。思考为什么返回指针比返回下标在某些场合更方便。