Skip to Content
介绍 C++ (Chinese Edition)
book

介绍 C++ (Chinese Edition)

by Frances Buontempo
March 2026
Intermediate
348 pages
3h 59m
Chinese
O'Reilly Media, Inc.
Content preview from 介绍 C++ (Chinese Edition)

第 10 章. 类 :成员变量 与成员函数

现在,您已经了解了 C++ 中的各种基本类型,包括数值类型、字符和字符串。 您已经多次使用过标准库中的类,包括std::向量 这样的类模板。 本章将向您展示如何编写自己的类。

类允许你将相关元素打包在一起。 例如,你可以将股票名称与开盘价以及生成或输入价格更新的方法打包在一起。 命名空间也能将相关函数和类型分组,但类为你提供了更多选择。 将元素封装到类中会生成一种新类型,这使你能够轻松地在交易游戏中添加新的股票类型。 你还可以为类命名以传达含义,这能让你的代码更易于阅读。

大约在 1979 年,由 Bjarne Stroustrup 设计的 C++()作为“带类的 C 语言”问世。 他发现类对于处理大型代码库非常有用,因为它们提供了一种更高层次的思考方式。 你可以将股票视为一个整体,而非仅仅是名称、价格以及获取新价格的方法。 此外,名称本身是一个std::string类,这比 C 风格的char指针具有更高的抽象层次。 正如你所见,C++ 远不止于类,但类是许多 C++ 代码库的基础组成部分。

让我们先创建一个类,从定义一些数据开始,然后逐步添加行为。 本章结束时,你将能够创建一个包含各种股票的std::向量。 届时,你将离开发一个更大型的交易游戏更近一步。

一个简单的类

是一种用户定义的类型,可以包含成员变量和成员函数。 类的最简单形式是结构体

创建一个名为stock.h 的新文件。 你将定义一个Stock类,包含名称、最新价格和波动率。在本章剩余部分中,你将扩展该类,并利用它生成各种股票的价格。

在头文件中声明一个结构体,使用关键字struct后跟名称。 对于简单的结构体,你可以使用大括号{} 来初始化数据成员,这被称为大括号初始化。 它为每个类型赋予默认值,例如,0.0 用于 double的默认值为 0.0。 类声明的最后一个大括号需以分号结尾,如下所示:

#pragma once

#include <string>

namespace stock_prices
{
    struct Stock 1
    { 2
        std::string name{}; 3
        double last_price{}; 4
        double volatility{}; 5
    }; 
}

声明一个名为Stock 的结构体

开始定义Stock ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

Navigating the midcareer plateau

Navigating the midcareer plateau

Uma Chingunde
Run Llama-2 Models

Run Llama-2 Models

Federico Castanedo

Publisher Resources

ISBN: 0642572352684