我有一個代碼,像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