So, I’m reading Schildt’s book 3rd edition about C++ and I’m doing all examples, but I have some PHP background and when I tried some stuff it occurs that it can not be compiled this way.I saw the Schildt’s solution, so I’ll give what I’ve tried to do and how it’s done in the book, what I need to know, is there any way to make it work adjusting my function?
Here’s what I’m trying
class card {
char author[40];
//char book[30];
int count;
public:
void store(char *auth,int ct);
void show();
};
void card::store(char *auth,int ct){
&author = *auth;
count = ct;
}
int main(){
card ob1, ob2;
ob1.store('Tolkin',10);
ob2.store('Pratchet',3);
ob1.show();
ob2.show();
return 0;
}
And here’s the Schildt’s solution:
class card {
char author[40];
int count;
public:
void store(char *auth,int ct);
void show();
};
void card::store(char *auth,int ct){
strcpy(author, auth);
count = ct;
}
I think the basic misunderstanding here is the way that C/C++ handle “char arrays” as strings. The
strcpyroutine copies the contents of a string, where the=assignment operator (applied tochar) copies a single character, or a pointer to the string.&author = *authwill look at theauthpointer, dereference it using*, and take the singlecharfound there, then take the address of (&) yourchar[]namedauthor, and try to change the address to thecharvalue.You could…
strcpyto copy the contents of the string (but, in new code, don’t use strcpy, usestrncpyinstead!)char* authorin your class would be assigned asauthor = auth; but then, ifauthisfree()d ordelete[]()ed later, you will have a pointer to memory that no longer contains your string, which is bad)std::stringobject instead of a C-stylechar[]for your string, which will behave more like a PHP string would.std::string authorcould be copied fromstd::string authusingauthor = auth.String-handling in C++ is a big subject, but you will definitely want to get a good understanding of the differences between “thing” and “pointer-to-thing” types … !
Also, in C++, you must use
""around strings, and''around singlechars. There is a lot less “magic” in a C/C++""string, though; only\xtype escape sequences work (for example, there is no"$var"substitution available). In Perl/PHP/Bourne/… you use''for non-escaped strings and""for escaped strings; in C++, sincecharandchar[]/std::stringare different types, they use the punctuation differently.