ठीक है। हम जानते हैं कि निम्नलिखित कोड संकलित नहीं किया जा सकता है।असाइनमेंट ऑपरेटर फ़ंक्शन में, सरणी ज्ञात रूप से
char source[1024];
char dest[1024];
// Fail. Use memcpy(dest, source, sizeof(source)); instead.
dest = source;
लेकिन, निम्न कोड को संकलित और सही तरीके से व्यवहार किया जा सकता है।
class A {
char data[1024];
};
A source;
B dest;
dest = source;
मैं सोच रहा था, ऑपरेटर असाइनमेंट फ़ंक्शन में, सरणी स्पष्ट रूप से memcpy होगा?
निम्नलिखित पूर्ण परीक्षण कोड हैं।
#include <cstdio>
#include <memory>
class A {
public:
char data[1024];
};
int main() {
{
A source;
A dest;
// Initialization
char *data = "hello world";
memcpy (source.data, data, strlen(data) + 1);
printf ("source.data = %s\n", source.data);
printf ("address source.data = %x\n", source.data);
// Works! Does this in the operator assignment function, memcpy is
// being performed implicitly on array.
dest = source;
printf ("dest.data = %s\n", dest.data);
printf ("address dest.data = %x\n", dest.data);
}
{
char source[1024];
char dest[1024];
// Initialization
char *data = "hello world";
memcpy (source, data, strlen(data) + 1);
printf ("source = %s\n", source);
printf ("address source = %x\n", source);
// '=' : left operand must be l-value
// dest = source;
// Works with memcpy.
memcpy(dest, source, sizeof(source));
printf ("dest = %s\n", dest);
printf ("address dest = %x\n", dest);
}
getchar();
}
//RESULT :
//source.data = hello world
//address source.data = 12fb60
//dest.data = hello world
//address dest.data = 12f758
//source = hello world
//address source = 12f344
//dest = hello world
//address dest = 12ef3c
इस मामले में बहुत सी चर्चा क्यों हुई [सी ++ क्यों structs के भीतर सरणी के सदस्यवार असाइनमेंट का समर्थन करता है लेकिन आमतौर पर नहीं?] (Http://stackoverflow.com/questions/3437110/why-does -c-support-memberwise-assign-of-arrays-in-structs-but-not-gene) –
std :: string का विरोध किया, आह? –