本文介绍了外部“C” struct - &gt;类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 以下程序是否符合标准?我用一些 编译器编译它并没有产生任何错误或警告,但这不是一个 演示。 有罪的部分是声明: externC struct X; 然后被定义为: class X {}; 我知道''extern'C"''只改变链接规范,但 转发C ++中的声明/通常/不允许使用不同的 class-keys。 问候, Daniele。 / *声明* / externC { struct X; X * new_X(); void delete_X(X *); } / * definitions * / class X {}; externC ; { X * new_X() { 返回新的X(); } void delete_X(X * p) { 删除p; } } // extern" C" int main() { X * p = new_X(); delete_X(p); 返回0; } <<<<<<<<<<<<<<<<< 解决方案 为了安全起见,我将从externC struct派生一个类。 externC struct X {...}; class X_impl:public X { // ... }; 但是这样功能的实现变得更加昂贵 (作为维护和bug的可能性),因为它需要转换为 正常工作。例如: externC struct X {/ * empty * /}; class X_impl:public X { // ... }; extern" C" { void foo( X * p) { X_impl * p2 = static_cast< X_impl *> (p); // ... } void delete_X(X * p) { 删除static_cast< X_impl *> (p); } } // externC 然而这是可能的解。谢谢你的回复。 Daniele 嗯,编程很昂贵,需要打字。 Is the following program standard-compliant? I''ve compiled it with somecompilers and no errors or warnings are produced, but this is not ademonstration. The "incriminated" part is the declaration: extern "C" struct X; that is then defined as: class X {}; I know that ''extern "C"'' change only the linkage specification, butforwarding declarations in C++ /usually/ don''t allow usage of differentclass-keys.Regards,Daniele. /* declarations */ extern "C" {struct X; X * new_X ();void delete_X (X *);} /* definitions */ class X {};extern "C" { X * new_X (){return new X ();} void delete_X (X * p){delete p;} } // extern "C" int main (){X * p = new_X ();delete_X (p);return 0;} <<<<<<<<<<<<<<<< 解决方案 To be on the safe side I would derive a class from an extern "C"struct. extern "C" struct X { ... }; class X_impl : public X{// ...}; But in this way the implementation of functions become more expensive(as maintenance and probability of bugs), because it needs casting toworks properly. E.g.: extern "C" struct X { /* empty */ }; class X_impl : public X{// ...}; extern "C"{ void foo (X * p){X_impl * p2 = static_cast<X_impl *> (p);// ...} void delete_X (X * p){delete static_cast<X_impl *> (p);} } // extern "C" However this is a possible solution. Thanks for your reply. Daniele Well, programming is expensive, it requires typing. 这篇关于外部“C” struct - &gt;类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-23 06:05