我來自 OOP 背景,并且一直在努力實作我所需要的最佳(速度明智)方式。
我定義了以下結構:
struct Vehicle {
int A;
int B;
}
我想要一些其他的結構,比如:
// is Vehicle
struct Bike {
int C;
}
// is Vehicle
struct Car {
int D;
}
最后我有一個功能:
void f(struct Vehicle vehicles[], int nVehicles) {
for(int i=0;i<nVehicles; i){
struct Vehicle v = vehicles[i];
//if v is a car do something
//else if a bike do something else
}
}
它接受一個陣列Vehicle作為引數,這些可以是任何bike一個car。
在f我需要訪問A,如果有B或如果有車。我該如何實施?CbikeD
現在我已經完成了以下作業,但我認為效率很低而且很糟糕:
struct Bike {
int A;
int B;
int C;
}
struct Car {
int A;
int B;
int D;
}
struct Vehicle {
char* vehicleType;
struct Bike;
struct Car;
}
void f(struct Vehicle vehicles[], int nVehicles) {
for(int i=0;i<nVehicles; i){
struct Vehicle v = vehicles[i];
char *vehicleType = v.vechicleType
if(strcmp(vehicleType, "Bike")==0) {
// Do something
} else if(strcmp(vehicleType, "Car")==0) {
// Do something else
}
}
}
我應該注意我定義了一次結構并且從不修改它們的屬性,我只是在閱讀它們。
uj5u.com熱心網友回復:
它主要在評論中說,但這里是對所說內容的處理(我沒有使用任何typedefs,但我個人會使用)。
所以,第 1 點,使用 aenum作為你的vehicleType,第 2 點,avehicle不能同時是 aCar和 aBike所以這是使用 aunion來節省空間的好地方。
所有這些都導致我們這樣:
enum VEHICLE_TYPE { bike, car };
struct Vehicle
{
enum VEHICLE_TYPE vehicleType;
union u
{
struct Bike
{
int top_speed;
} Bike;
struct Car
{
int number_of_seats;
} Car;
} u;
} Vehicle;
然后你可能會這樣做:
int main ()
{
struct Vehicle v;
v.vehicleType = bike;
v.u.Bike.top_speed = 100;
...
}
大多數人(包括我自己!)可能不同意我在這里(錯誤)使用大寫和小寫的方式。抱歉,有點著急。
uj5u.com熱心網友回復:
我會使用 C 風格的指標轉換:
struct Bike {
int A;
int B;
int C;
};
struct Car {
int A;
int B;
int D;
};
struct Vehicle {
const char* vehicleType;
};
void f(struct Vehicle vehicles[], int nVehicles) {
for (int i = 0; i < nVehicles; i) {
Vehicle v = vehicles[i];
const char* vehicleType = v.vehicleType;
if (strcmp(vehicleType, "Bike") == 0) {
Bike* b = (Bike*)&v;
//Do what you need with 'Bike' now
b->A = 1; //For example
b->B = 1; //For example
b->C = 1; //For example
}
else if (strcmp(vehicleType, "Car") == 0) {
Car* c = (Car*)&v;
//Do what you need with 'Car' now
c->D = 2; //For example
}
}
}
uj5u.com熱心網友回復:
對于 C 結構繼承,我體驗最多的基本模式如下:
struct Vehicle {
int A;
int B;
};
struct Bike {
struct Vehicle;
int C;
};
struct Car {
struct Vehicle;
int D;
};
每當Vehicle更改時,子類都會自動獲取這些更改。
對于自省部分,最常見的是特定領域,正如其他人指出的那樣,例如在 Objective-C 中實作的。這個想法是在層次結構的頂級類中定義該欄位:
struct Object{
int whatami;
};
struct Vehicle {
struct Object;
int A;
int B;
};
關于軟體工程 Stackexchange 的一些相關問題可能會引起人們的興趣:
OO C 公共和私有函式的典型命名約定是什么?
C 程式的 OO 最佳實踐
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/478936.html
