C中的类(不是C ++)
我在一个西class牙语网站( http://trucosinformaticos.wordpress.com/2010/12/12/programacion-orientado-a-objetos-en-c/ )中发现了这个黑客攻击。
我想在C(而不是C ++)中创建一个“类”,但是当我编译时,我获得了下一个错误:
source.c(25): warning C4047: 'function' : 'Car' differs in levels of indirection from 'Car *' source.c(25): warning C4024: 'changeYears' : different types for formal and actual parameter 1
这是我的代码:
#include typedef struct Car* Car; // class Car // { struct Car { int years; //char model[100]; }; void changeYears(Car this, int years) { this->years = years; } // } int main(void) { Car my_cars[10]; //nombrar(mis_alumnos[0], "Pepito"); changeYears(&my_cars[0], 6); // My car has now 6 years return 0; }
我同意@Oli Charlesworth的说法,将指针隐藏在typedef
后面是一种让自己和他人混淆的简单方法。
但是,要使代码编译和工作,您只需删除my_cars
前面的&
运算符my_cars
。 您还需要为这些指针分配内存。 我会说你之所以犯这个错误的原因是你把自己与指针隐藏混淆了。
#include typedef struct Car* Car; struct Car { int years; //char model[100]; }; void changeYears(Car this, int years) { this->years = years; } int main(void) { // An array of struct char* Car my_cars[10]; int i; for (i = 0; i < 10; i++) my_cars[i] = malloc(sizeof(struct Car)); changeYears(my_cars[0], 6); // My car has now 6 years return 0; }
这是一种更合理的方法来实现它而不隐藏指针。
#include typedef struct { int years; //char model[100]; } Car; void changeYears(Car* this, int years) { this->years = years; } int main(void) { Car my_cars[10]; changeYears(&my_cars[0], 6); // My car has now 6 years return 0; }
我认为这就是你要找的东西:
(更清洁的实现,你想要的)
码:
#include #include #include typedef struct { int years; } Car; void changeYears(Car *this, int years) { this->years = years; } int main(void) { Car *car = malloc(sizeof(Car)); changeYears(car, 2014); printf("car.years = %d\n", car->years); free(car); return 0; }
OUTPUT:
car.year = 2014