私はstd :: vectorを配列の代わりにC++で使用することができ、しかし、この質問は実用的なものではありません。それは私の理解のためです。私はmemcpy()操作の実際の値の代わりに '0'を参照してください。このテストコードで何が間違っていますか?コンストラクタの整数配列に対するmemcpy()操作は、C++で予期せぬ出力を与えます
#include <stdint.h>
#include <cstring>
#include <cstdlib>
#include <iostream>
using namespace std;
class IntList
{
private:
int* m_anList; //I could use std::vector in practical applications I know
//However I want to experiment what happens
public:
IntList(const int m_anList[]){
this->m_anList = new int[sizeof(m_anList+1)]; //heap allocation - since bad idea to copy on stack
memcpy((int*)this->m_anList,m_anList,sizeof(m_anList+1)); //<-This does not look right
cout << this->m_anList[4] << endl;//<- gives '0'??? Not expected
}
~IntList(){
if(this->m_anList)
{
delete[] this->m_anList;
}
}
int& operator[] (const int& nIndex);
};
int& IntList::operator[] (const int& nIndex)
{
cout << this->m_anList[nIndex] << endl; //<- gives '0'??? Not Expected
return this->m_anList[nIndex];
}
int main()
{
int test_array[10] = {1,2,3,4,5,6,7,8,9};
IntList test(test_array);
test[2];
return 0;
}
私はこれを以前char *で使用していました。 char = 1 Byte、int = 2 Byteではなくmemcpyがvoid *に適用されます。
更新されたコード/ソリューション(ロブのおかげで(いくつかのミスの私の最も基本的なことを指摘WHO)と答えたみんな。私はCS卒業生はないですが、将来的にはより良いコードしようとするだろう。おかげで再び。)
#include <stdint.h>
#include <cstring>
#include <cstdlib>
#include <iostream>
//#include <algorithm>
//#include <vector>
using namespace std;
class IntList
{
private:
int* m_anList; //I could use std::vector in practical applications I know
//However I want to experiment what happens
public:
IntList(const int m_anList[], std::size_t n){
this->m_anList = new int[n * sizeof(int)];
memcpy(this->m_anList,m_anList,n*sizeof(m_anList[0]));
cout << this->m_anList[4] << endl;
}
~IntList(){
if(this->m_anList)
delete[] this->m_anList;
}
int& operator[] (const int& nIndex);
};
int& IntList::operator[] (const int& nIndex)
{
cout << this->m_anList[nIndex] << endl;
return this->m_anList[nIndex];
}
int main()
{
int hello[10] = {1,2,3,4,5,6,7,8,9};
//cout << hello[3] << endl;
IntList test(hello,10);
test[2];
return 0;
}
あなたがこれから学ぶことができる最高のことは、うまく行かなかった不吉なことをするように導いたことです。あなたの将来の同僚を検討してください。彼らは生の配列とmemcpuでそれらをさせる場合、彼らは同じ方法を汚すでしょう。 –
'sizeof(m_anList + 1)'は何になると思いますか? "* int = 2 Byte *"過去15年間の主要なプラットフォームではありません... – ildjarn
あなたの質問には関係ありませんが、メンバ関数のパラメータにメンバー変数(m_anList)と同じ名前を付けることは災害のレシピです。 –