[c++] Which one: structure or class

有了类,还要结构体做什么?


一、结构体de构造函数

构造函数在结构体内元素比较多的时候会使得代码精炼,因为可以不需要临时变量就可以初始化一个结构体,而且整体代码更简洁。这就是构造函数的精妙之处。

结构体中,也可以设置一些默认值,比如年假什么的.

复制代码
#include<stdio.h>
struct Point{ int x, y; Point(){} // 用以不经初始化地定义pt[10] Point(int _x, int _y): x(_x), y(_y) {} // 用以提供x和y的初始化 }pt[10];

int main(){ int num = 0;
for(int i = 1; i <= 3; i++){ for(int j = 1; j <= 3; j++){ pt[num++] = Point(i, j); // <-- 直接使用构造函数,看上去干净了许多 } }
for(int i = 0; i < num; i++){ printf("%d,%d\n", pt[i].x, pt[i].y); }
return 0; }
复制代码

 

 

二、结构体作为参数

与类对象一样,结构体变量也可以通过值、引用和常量引用传递给函数。默认情况下,它们使用值传递.

加上const,常量引用传入即可.

复制代码
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
struct Invltem// Holds data for an inventory item { int partNum; // Part number string description; // Item description int onHand; // Units on hand double price; // Unit price };
// Function prototypes void getltemData(InvItem &) ; void showItem(const InvItem &);
int main() { InvItem part; // Define an Invltem structure variable. getItemData(part); showItem(part);
return 0; }
void getItemData(InvItem &item) { cout << "Enter the part number: "; cin >> item.partNum; cout << "Enter the part description: "; cin.get(); getline (cin, item.description); cout << "Enter the quantity on hand: "; cin >> item.onHand; cout << "Enter the unit price: "; cin >> item.price; }
void showItem(const InvItem &item) { cout << fixed << showpoint << setprecision(2) << endl; cout << "Part Number : " << item.partNum << endl; cout << "Description : " << item.description << endl; cout << "Units On Hand : " << item.onHand << endl; cout << "Price : $" << item.price << endl; }
复制代码

 

 

三、结构体de继承

Bear in mind you can use virtual inheritance with structs. They are THAT identical.

struct能继承吗? 能!!

struct能实现多态吗? 能!!!

 

  • 不使用虚继承

复制代码
struct Animal {
    virtual ~Animal() = default;
    virtual void Eat() {}
};

struct Mammal: Animal {
    virtual void Breathe() {}
};

struct WingedAnimal: Animal {
    virtual void Flap() {}
};

// A bat is a winged mammal
struct Bat: Mammal, WingedAnimal {};

Bat bat;
复制代码

强制类型转换,告诉编译器,访问"祖父类"是通过的哪个"父类".

Bat b;
Animal
& mammal = static_cast<Mammal&>(b); Animal& winged = static_cast<WingedAnimal&>(b);

 

  • 使用虚继承

复制代码
struct Animal {
    virtual ~Animal() = default;
    virtual void Eat() {}
};

// Two classes virtually inheriting Animal:
struct Mammal: virtual Animal {
    virtual void Breathe() {}
};

struct WingedAnimal: virtual Animal {
    virtual void Flap() {}
};

// A bat is still a winged mammal
struct Bat: Mammal, WingedAnimal {};
复制代码

 

End.

posted @   郝壹贰叁  阅读(171)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示