[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 @ 2020-04-07 09:52  郝壹贰叁  阅读(173)  评论(0)    收藏  举报