我用一个模板定义了一个类,该模板定义了一个通用数组类型T个元素N.我有另一个有这个数组实例作为成员的类。当我尝试使用setString函数时,我传递的数组从任意的15个元素到4个元素。作为参数传递给C++类时的内存丢失
// testClassArraySize.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <stdio.h>
#include <iostream>
#include <istream>
#include <ostream>
using namespace std;
template<class T, int N>
class CArray {
public:
T arr[N];
CArray(void) {/*arr=(T *)malloc(sizeof(T)*N);*/
if (arr == NULL) {
cout << "allocation error\n";
}
}
;
//CArray (int n) {arr=new T [n]; if(arr==NULL){exit(0); cout<<"allocation error\n";}};
CArray operator=(const T *);
T operator[](const int i) {
return arr[i];
}
;
};
template<class T, int N>
CArray<T, N> CArray<T, N>::operator=(const T *srce) {
size_t x = sizeof(arr);
size_t y = sizeof(srce);
for (int j = 0; j < sizeof(arr); j++) {
if (j > sizeof(srce)) {
arr[j] = 0;
break;
}
arr[j] = srce[j];
}
return *this;
}
class myTestClass {
private:
CArray<char, 15> myString;
public:
myTestClass setString(char set[15]) {
myString = set;
size_t x = sizeof(set);
return *this;
}
;
};
int main() {
myTestClass myObject;
myObject.setString("helloWorld");
return 0;
}
有没有人有任何想法为什么?
当然,您还没有启用任何编译器警告,是吗?这些可以非常有帮助。 –
为这个想法+1,但MSVC10没有任何。你期望哪一个? – dyp