2017-04-07 5 views
0

私の必要性は、他のものに類似の構造を割り当てることです。ちょうど名前が異なります。 同じ名前の場合は、=(代入)を直接使用できます。 私はビットをコピーするので、memcopyを使用したくありません。異なるタイプの2つの構造を割り当てることは可能ですか?

struct first{ 
int i; 
char c; 
} 
struct second{ 
int i; 
char c; 
//we can overload assignment operator to copy field. 
void operator = (struct first& f) 
    i=f.i; 
    c=f.c; 
} 

int main() 
{ 
    struct first f; 
    f.i=100; 
    f.c='a'; 
    struct second s=f; 
} 

コンパイルエラーです。 エラー:「最初」から非スカラー型「秒」への変換が要求されました。

可能かどうかわかりません。

+1

ここでは割り当てません。あなたはオブジェクトをコピーしています。だからコピーコンストラクタが必要です –

+0

初期化!=割り当て。 'first'を引数とする' second'のコンストラクタを書くか、 'first'の中で' second'に変換演算子を書いてください。 –

+0

あなたはcast-through-a-unionイディオムを使うこともできますし、コンパイラがあなたのコードを壊す可能性のあるエイリアシング最適化を行わないようにすることもできます。または単にmemcpy、非常にブルートフォース。 –

答えて

1

次のように使用します。その後、それは動作します。または、コピーコンストラクタを作成します。

second s; // No need to use struct in C++ 
s = f; 

ところで、適切なインターフェース:

struct second{ 
    int i; 
    char c; 
    second(first const& f) : i(f.i), c(f.c) {} 

    ... 

}; 

は、代入演算子、使用を使用するには:

#include <iostream> 
using namespace std; 

struct first{ 
int i; 
char c; 
}; 
struct second{ 
int i; 
char c; 
//we can overload assignment operator to copy field. 
void operator = (struct first& f) 
{ 
    i=f.i; 
    c=f.c; 
} 
}; 

int main() 
{ 
    struct first f; 
    f.i=100; 
    f.c='a'; 
    struct second s; 
    s=f; 
} 
5

あなたが

struct second s=f; 

などとして使用するコンストラクタが必要の実装と実装関数は次のようになります。

second& operator=(first const& f) 
{ 
    i=f.i; 
    c=f.c; 
    return *this; 
} 
+0

このような迅速かつ有益な返答をありがとう。 私の悪い、それは割り当てであることを覚えていたが、そのコピー:)。 – user2761565

関連する問題