我有一个代码,像Java那样做OOP。
我已将界面和实现分隔开,文件名为demo.h
和demo.c
。多个结构变量的值是无意的相同
demo.h
#ifndef DEMO_H
#define DEMO_H
typedef struct {
/*
This is the variable that will be set by setter method
and its value will be extracted by getter method.
This variable must not be directly accessible by the programmer.
*/
int num;
void (* setNum)(int); // This function will set the value of variable "num".
int (* getNum)(); // This function will return the value of variable "num".
} *Demo; // As objects in java are always called by reference.
Demo newDemo(); // This function will create an instance of class(struct here) Demo and return.
/* This is equivalent to:
Demo obj = new Demo();
int java.
I want my users to create instance of this class(struct here) like this:
Demo obj = newDemo();
here in this code.
*/
#endif
和实现:
demo.c
#include <stdlib.h>
#include "demo.h"
Demo demo; /* I have created a global variable so that it is accessible
in setNum and getNum functions. */
void setNum(int num) {
demo->num = num; // This is where the global demo is accessed.
}
int getNum(Demo obj) {
return demo->num; // This is where the global demo is accessed.
}
Demo newDemo() {
Demo obj; // This will be the returned object.
obj = (Demo)malloc(sizeof(*obj)); /* Allocating separate memory to
obj each time this function is called. */
/* Setting the function pointer. */
obj->setNum = setNum;
obj->getNum = getNum;
/* As obj is at different memory location every time this function is called,
I am assigning that new location the the global demo variable. So that each variable
of the Demo class(struct here) must have a different object at different memory
location. */
demo = obj;
return obj; // Finally returning the object.
}
这是多么我已经实现了main
功能:
主.c
#include "demo.h"
#include <stdio.h>
int main() {
void displayData(Demo);
Demo obj1 = newDemo();
Demo obj2 = newDemo();
Demo obj3 = newDemo();
obj1->setNum(5);
obj2->setNum(4);
obj3->setNum(12);
displayData(obj1);
displayData(obj2);
displayData(obj3);
return 0;
}
void displayData(Demo obj) {
int num = obj->getNum();
fprintf(stdout, "%d\n", num);
}
在编译和执行我的Mac书临:
> gcc -c demo.c
> gcc main.c demo.o -o Demo
> ./Demo
输出是:
12
12
12
但所需的输出是:
5
4
12
什么我做错了吗?
请帮忙。
我不希望我的用户的结构指针作为参数传递为:
Demo obj = newDemo();
obj->setName(obj, "Aditya R.Singh"); /* Creating the program this way was successful as my
header file had the declaration as:
typedef struct demo {
int num;
void (* setNum)(struct demo, int); // This is what I don't desire.
void (* getNum)(struct demo); // This is what I don't desire.
} *Demo;
I want to keep it like the way it is in my current
demo.h*/
/* I don't want to pass obj as an argument. All I want to do this is this way. */
obj->setName("Aditya R.Singh");
是否有任何可能的方式来做到这一点,得到需要的结果?
请大家帮忙,谢谢!
你从不在任何地方设置全局的'demo'。我想你希望C在你的'obj-> setName'调用中为你设置它,但它不会; C没有方法。 – 2014-11-14 14:18:51
“我有一个像Java一样的OOP代码” - >停在那里。不,你没有; C不支持这一点。你可以在C中获得OOP,但它永远不会看起来像Java的语法。 *在C中看起来像Java的代码将不可避免地使用对象,或者不使用实例方法。无论哪种方式,它不会是面向对象的。 – Leushenko 2014-11-14 14:55:19