2.
// In C, it is correct:3. // 1)
int *pr=NULL;
// in C++, it is correct:
int *pr=0;
// if you want keep
int *pr=NULL;
//in C++ code, you should #include<cstdlib>
int a=10;//2)
int b=20;
int const *pt=&a; // same as: const int *pt=&a ;
*pt=11; //error
pt=&b; // correct
int a=10;4. conversion between string and char
int b=20;
int *const pt=&a;
*pt=11; //correct
pt=&b; // error
//1)5. avoid repeating include, also a better file framework(at least for me)
char * ch="caozhiguang";
string str(ch); // from char to string;
string str=ch; // same with above
//2)
string str("caozhiguang");
char *ch;
ch=str.c_str(); // from string to char;
//Zhiguang.h6. create one object for the class
#include <string>
using namespace std;
#ifndef ZHIGUANG_H
#define ZHIGUANG_H
Class Zhiguang
{
public:
Zhiguang();
Zhiguang(string the_name, string the_addr);
string getinfo();
private:
string name;
string address;
static double salary;
}
#endif
//Zhiguang.cpp
//you'd better initialize the static var in this file
#include "Zhiguang.h"
salary=3500; //initialize the static var;
Zhiguang::Zhiguang() { }
Zhiguang::Zhiguang(string the_name, string the_addr) { }
string Zhiguang::getinfo(){ }
//main.cpp
#include "Zhiguang.h" // no need to include the cpp file
using namespace std;
int main()
{
Zhiguang zg;
// do whatever you want
}
//1)7. default constructor needed to initialize members of built-in type
Zhiguang zg;
zg.name;
zg.address;
zg.getinfo();
//2)
Zhiguang zg=Zhiguang();
zg.name;
zg.address;
zg.getinfo();
//3)
Zhiguang *zg=new Zhiguang();
zg->name;
zg->address;
zg->getinfo();
Zhiguang() : name("zhiguang"), address("Singapore"){ }
Note: for the real initialize order, it would be based on the declaration order in the class declaration.e.g:
private:in this case, the default constructor would initialize the address first even it is listed in the second place in the constructor.
string address;
string name;
8. 1) if the member method is const, it means it can not change the object's member variable;
2) for const member, there should be keyword const both in declaration and definition;
3) the const object can only use its const member, while non-const object can access both const and non-const members;
4) for non-const member method, this could not be changed while *this could;
for const member method, both this and *this could not be changed.
No comments:
Post a Comment