C++中通过struct和class定义自定义数据类型来管理多个变量,struct适用于简单数据聚合,class更适合封装复杂行为和状态,二者本质功能相同但默认访问权限不同,推荐结合std::vector等标准库容器高效管理对象集合。

在C++中,要定义自定义数据类型来管理多个变量,我们主要依赖
struct
class
从我的经验来看,当你发现有多个变量总是需要一起出现,并且它们共同描述了一个“事物”时,比如一个人的姓名、年龄、身高,或者一本书的标题、作者、出版年份,那么这就是定义一个自定义数据类型的好时机。
使用struct
struct
struct
public
立即学习“C++免费学习笔记(深入)”;
#include <string>
#include <iostream>
// 定义一个表示“学生”的结构体
struct Student {
std::string name;
int age;
double grade;
// 结构体也可以有成员函数,尽管通常更倾向于用类
void printInfo() {
std::cout << "姓名: " << name << ", 年龄: " << age << ", 成绩: " << grade << std::endl;
}
};
// 使用示例
// int main() {
// Student s1;
// s1.name = "张三";
// s1.age = 20;
// s1.grade = 88.5;
// s1.printInfo();
//
// Student s2 = {"李四", 22, 92.0}; // C++11 列表初始化
// s2.printInfo();
// return 0;
// }使用class
class
struct
class
private
private
public
#include <string>
#include <iostream>
// 定义一个表示“书籍”的类
class Book {
private: // 数据通常是私有的,这是封装的核心
std::string title;
std::string author;
int publicationYear;
public: // 公共接口,用于与类的对象交互
// 构造函数:初始化对象时调用
Book(const std::string& t, const std::string& a, int year)
: title(t), author(a), publicationYear(year) {
// 可以在这里添加一些验证逻辑,比如确保年份是合理的
if (publicationYear < 1440 || publicationYear > 2024) {
std::cerr << "警告:书籍 '" << title << "' 的出版年份可能不合理。" << std::endl;
}
}
// Getter 方法:获取私有数据
std::string getTitle() const { return title; }
std::string getAuthor() const { return author; }
int getPublicationYear() const { return publicationYear; }
// Setter 方法:修改私有数据(如果允许的话)
void setPublicationYear(int year) {
if (year >= 1440 && year <= 2024) { // 再次进行验证
publicationYear = year;
} else {
std::cerr << "错误:无效的出版年份。" << std::endl;
}
}
// 其他行为方法
void displayInfo() const {
std::cout << "书名: " << title << ", 作者: " << author << ", 出版年份: " << publicationYear << std::endl;
}
};
// 使用示例
// int main() {
// Book b1("C++ Primer", "Stanley B. Lippman", 2012);
// b1.displayInfo();
//
// b1.setPublicationYear(2020); // 修改年份
// b1.displayInfo();
//
// b1.setPublicationYear(1000); // 尝试设置无效年份
// b1.displayInfo(); // 年份不会改变,因为setter有校验
// return 0;
// }选择
struct
class
struct
class
std::tuple
这是一个很好的问题,我个人在初学C++时也曾有过类似的疑惑。确实,数组可以管理多个同类型变量,
std::tuple
struct
class
首先,数组是为同质数据设计的。如果你想存储一个班级所有学生的年龄,
int ages[50];
data[0]
data[1]
其次,std::tuple
std::tuple<std::string, int, double> studentInfo;
std::get<0>(studentInfo)
0
tuple
而
struct
class
student.name
book.getTitle()
std::tuple
struct
class
struct
class
这个问题常常困扰初学者,甚至一些有经验的开发者也会偶尔混淆。但说实话,在C++中,
struct
class
唯一的、真正的语法区别在于:
默认成员访问权限:
struct
public
class
private
struct
class
public
默认继承访问权限:
struct
struct
class
public
class
struct
class
private
class Derived : public Base
除了这两点,
struct
class
struct
class
那么,既然功能一样,为什么C++要保留两种关键字呢?这主要是出于历史原因(
struct
struct
struct
class
class
所以,选择
struct
class
struct
class
定义了自定义数据类型之后,我们通常不会只创建一个对象,而是会创建大量这样的对象,并将它们组织起来。C++标准库为我们提供了非常强大的容器,它们是管理对象集合的利器。
最常用、也是最推荐的容器是
std::vector
#include <vector>
#include <string>
#include <iostream>
#include <algorithm> // 用于 std::sort
// 假设我们有之前定义的 Student 结构体
struct Student {
std::string name;
int age;
double grade;
void printInfo() const { // 注意这里加了 const
std::cout << "姓名: " << name << ", 年龄: " << age << ", 成绩: " << grade << std::endl;
}
};
// 假设我们有之前定义的 Book 类
class Book {
private:
std::string title;
std::string author;
int publicationYear;
public:
Book(const std::string& t, const std::string& a, int year)
: title(t), author(a), publicationYear(year) {}
std::string getTitle() const { return title; }
std::string getAuthor() const { return author; }
int getPublicationYear() const { return publicationYear; }
void displayInfo() const {
std::cout << "书名: " << title << ", 作者: " << author << ", 出版年份: " << publicationYear << std::endl;
}
};
int main() {
// 管理 Student 对象的集合
std::vector<Student> students;
// 添加学生对象
students.push_back({"张三", 20, 88.5});
students.push_back({"李四", 22, 92.0});
students.emplace_back("王五", 21, 78.0); // emplace_back 可以直接在容器内部构造对象,更高效
std::cout << "--- 学生列表 ---" << std::endl;
for (const auto& s : students) { // 使用范围for循环遍历
s.printInfo();
}
// 对学生按成绩排序(需要提供比较函数)
std::sort(students.begin(), students.end(), [](const Student& a, const Student& b) {
return a.grade > b.grade; // 降序排列
});
std::cout << "\n--- 按成绩排序后的学生列表 ---" << std::endl;
for (const auto& s : students) {
s.printInfo();
}
// 管理 Book 对象的集合
std::vector<Book> library;
library.emplace_back("Effective C++", "Scott Meyers", 1991);
library.emplace_back("Clean Code", "Robert C. Martin", 2008);
std::cout << "\n--- 图书馆藏书 ---" << std::endl;
for (const auto& book : library) {
book.displayInfo();
}
// 查找特定书籍
std::string searchTitle = "Clean Code";
auto it = std::find_if(library.begin(), library.end(), [&](const Book& b){
return b.getTitle() == searchTitle;
});
if (it != library.end()) {
std::cout << "\n找到书籍: ";
it->displayInfo();
} else {
std::cout << "\n未找到书籍: " << searchTitle << std::endl;
}
return 0;
}除了
std::vector
std::list
std::list
std::map
std::unordered_map
std::map
std::unordered_map
std::set
std::unordered_set
选择合适的容器,能让你的程序在管理自定义类型对象集合时,既高效又易于维护。这真的是C++标准库的强大之处,它提供了一套非常成熟且经过优化的工具,让你能专注于业务逻辑,而不是底层的数据结构实现。
以上就是C++如何定义自定义数据类型管理多个变量的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号