70,020
社区成员




class CMyTest1
{
private:
int m_nTest1;
public:
CMyTest1()
{
this->m_nTest1 = 1;
printf("构造函数\n");
}
~CMyTest()
{
printf("析构函数\n");
}
int OnTest(int nVal)
{
this->m_nTest1 = nVal;
return 1;
}
};
/// 改成结构体如下.
typedef struct tag_MyTest
{
int m_nTest1;
void (*MyTest)(struct tag_MyTest *pData);
void (*_MyTest)(struct tag_MyTest *pData);
int (*OnTest)(struct tag_MyTest *pData, int nVal);
}MYTEST;
void MY_MyTest1(MYTEST *pData)
{
if(!pData)
return;
pData->m_nTest1 = 1;
printf("构造函数\n");
}
void MY__MyTest(MYTEST *pData)
{
if(!pData)
return;
printf("析构函数\n");
}
int MY_OnTest(MYTEST *pData, int nVal)
{
if(!pData)
return 0;
pData->m_nTest1 = nVal;
return 1;
}
int MYTEST_Init(MYTEST *pData)
{
if(!pData)
return 0;
// 所有函数都要调用.
pData->MyTest = MY_MyTest1;
pData->_MyTest= MY__MyTest;
pData->OnTest = MY_OnTest;
}
// 使用如:
int main_struct() //用结构体.
{
MYTEST test;
MYTEST_Init(&test); // 每个都必须调用.
test.MyTest(&test); // 模拟构造函数.手动调用.
test.OnTest(&test, 1000); // 函数调用.
test._MyTest(&test); // 模拟析构函数,手动调用.
}
int main_class() // 用类.
{
CMyTest1 test;
test.OnTest(1000);
}
class Foo
{
public:
Foo();
Foo(int value);
~Foo();
void show();
int member;
};
class Bar: Foo
{
public:
Bar();
~Bar();
}
Foo::Foo(): member(0) {}
Foo::Foo(int value): member(value) {}
void Foo::show() { cout<<value<<endl; }
可以写个这样的C:
typedef struct
{
int member;
} Foo;
typedef struct
{
Foo parent;
} Bar;
Foo* Foo_new()
{
return (Foo*) malloc(sizeof(Foo));
}
void Foo_construct(Foo* self)
{
self->member = 0;
}
void Foo_construct_with_value(Foo* self, int value)
{
self->member = value;
}
void Foo_show(Foo* self)
{
printf("%d\n",self->member);
}
void Foo_destruct(Foo* self)
{}
void Foo_release(Foo* self)
{
free(self);
}
Bar* Bar_new()
{
return (Bar*) malloc(sizeof(Bar));
}
void Bar_construct(Bar* self)
{
Foo_construct(self->parent);
}
void Bar_destruct(Bar* self)
{
Foo_destruct(self->parent);
}
void Bar_release(Bar* self)
{
free(self);
}
然后,假设你原来有这样的代码:
void main()
{
Foo obj1;
Bar* obj2 = new Bar();
}
现在就得变成这样:
void main()
{
Foo obj1;
Foo_construct(&obj1);
Bar* obj2 = Bar_new();
Bar_construct(obj2);
Foo_destruct(&obj1);
Bar_destruct(obj2);
Bar_release(obj2);
}
改了函数声明和定义之后,调用的地方也要改吧?C++成员函数里面有this指针的。除非用全局变量。我以前把一段C++改成过C
将数据和函数分开成两部分 数据部分假设叫 struct A 所有原来的非静态函数都有更改 函数签名 原来:xxx aFun( parmlist)==>xxx aFun(A* pA,parmlist) 函数体内所有的原来类成员变量改为:pA->yyy 所有的原来成员函数改为: aFun(pA,....) 你们老师也真是脑袋有问题,如果你的类比较复杂,够你喝一壶的了
把类除掉啊!用普通函数也是可以的啊! 只是代码量会多一点而已!
贴出来看看 帮你想想怎么改 这么笼统怎么改