C++とCでは、void構造体へのポインタを介して別の関数に異なる関数を渡すことができます。誰もがこの作業を行うか、それも可能であれば方法を知ってい異なる構造体へのポインタを関数に渡すにはどうすればよいですか?
#include <iostream>
using namespace std;
struct S1 {
static constexpr int n=1;
static constexpr double v=1.2;
};
struct S2 {
static constexpr int n=2;
static constexpr double v=3.4;
};
typedef void *Vp; // this would be (*Vp)() for functions
void func(Vp p) {
cout << "n=" << p->n << " v=" <<'\n'
// (fails here with error: 'Vp {aka void*}' is not
// a pointer-to-object type)
}
int main() {
struct S1 s1;
struct S2 s2;
cout <<"main: using first data\n";
func(&s1);
cout <<"main: using second data\n";
func(&s2);
return 0;
}
:私はこの単純な例のように、関数に構造体を渡して、同じことをやりたいですか?
同様の質問が以前に尋ねたが、答えは私を助けていない: passing different structs to a function(using void *)
私は1つの構造体を使用し、別のインスタンスを作成する方が良いだろうけど、私はすでに構造体にロードされたデータのたくさんのヘッダを持っていますこちらです。
構造体のポイントは何ですか? voidポインターを使うのは、通常、非常に悪いデザインの良い兆候です。 PS。 'p-> n'は意味を持たない。 –
' void * 'はすべての情報を失う。あなたは何を期待しましたか? –