类C(不是C ++) [英] Class in C (not C++)
问题描述
我发现这个黑客在网站的西班牙语(的http://trucosinformaticos.word$p$pss.com/2010/12/12/programacion-orientado-a-objetos-en-c/).
我要创建C(不是C ++)一个类,但是当我编译,我得到下一个错误:
由source.c(25):警告C4047:'功能':'车',从间接的水平不同,汽车*'
由source.c(25):警告C4024:'changeYears:不同类型的正式和实际参数1
这是我的code:
的#include<&string.h中GT;typedef结构租车*汽车;//类车
// {
汽车结构
{
INT年;
//字符模型[100];
};
无效changeYears(车载此,INT年)
{
这 - >年=年;
}
//}
INT主要(无效)
{
车my_cars [10];
// nombrar(mis_alumnos [0],Pepito);
changeYears(安培; my_cars [0],6); //我的车现在已经6年 返回0;
}
我会@Oli查尔斯沃思同意隐藏的typedef
是一个非常简单的方法,后面的指针混淆自己和他人。
不过,为了使您的code编译和工作,你可以删除&安培;
运营商面前 my_cars
。您还需要为这些指针分配内存。我会说你为什么摆在首位犯了这个错误的原因是你自己的困惑与指针躲藏起来。
的#include<&string.h中GT;typedef结构租车*汽车;汽车结构
{
INT年;
//字符模型[100];
};
无效changeYears(车载此,INT年)
{
这 - >年=年;
}
INT主要(无效)
{
//结构char类型的数组*
车my_cars [10];
INT I;
对于(I = 0; I&小于10;我+ +)
my_cars [I] =的malloc(sizeof的(结构租车));
changeYears(my_cars [0],6); //我的车现在已经6年 返回0;
}
下面是实现这个没有隐藏三分球更合理的方式。
的#include<&string.h中GT;typedef结构
{
INT年;
//字符模型[100];
}车;
无效changeYears(车载*此,INT年)
{
这 - >年=年;
}
INT主要(无效)
{
车my_cars [10];
changeYears(安培; my_cars [0],6); //我的车现在已经6年
返回0;
}
I've discovered this hack in a website in Spanish (http://trucosinformaticos.wordpress.com/2010/12/12/programacion-orientado-a-objetos-en-c/).
I want create a "class" in C (not C++), but when I compile, I obtain the next errors:
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
This is my code:
#include <string.h>
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;
}
I would agree with @Oli Charlesworth that hiding a pointer behind a typedef
is a very easy way to confuse yourself and others.
However, to make your code compile and work, you can just remove the &
operator in front of my_cars
. You also need to allocate memory for those pointers. I would say the reason why you made this mistake in the first place was that you confused yourself with the pointer hiding.
#include <string.h>
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;
}
Here is a more reasonable way to implement this without hiding pointers.
#include <string.h>
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;
}
这篇关于类C(不是C ++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!