关于C++ CLASS的一些杂记
- class中有const声明的成员变量时,只能在构造函数列表中进行初始化
private:
const int id;
SingleDog::SingleDog(int id_, char* name_):id(id_){...}
多个const的声明暂且未知
- class中有static声明的成员变量时,该变量为所有对象公有,均可对其进行修改。故只能在class外对其进行一次初始化
private:
int id_;
Date *birthDate;
static int numberOfObjects;
int Person::numberOfObjects=0;
而只有带有static标识符的成员函数才可以返回static的成员变量
static int getNumberOfObjects();
3.成员函数的参数如果是对其他对象的引用则可以直接访问其成员变量
Vector::Vector(const Vector& otherVec){
name=otherVec.name;
dimension=otherVec.dimension;
param=new int[dimension];
for(int i=0;i<otherVec.dimension;i++)
param[i]=(otherVec.param)[i];
cout<<"copy a vector called "<<name<<".\n";
}
4.(以下来自同一道坑题QAQ)
用this指针返回对当前对象的引用
list& list::sort(){
node *front, *back;
for(int i = 0;i < _size - 1;i++){
front = head -> next;
back = front -> next;
for(int j = 0;j < _size - 1 - i;j++){
if(front -> data > back -> data){
int temp=front -> data;
front -> data = back -> data;
back -> data = temp;
}
front = front -> next;
back = back -> next;
}
}
return *this;
}
这使得该成员函数后可接其他成员函数
cout << li.sort().toString() << endl;
5.其他类型的数据都可以变成string类型(必须使用C11标准)
std::string to_string(int value);
std::string to_string(long value);
std::string to_string(long long value);
std::string to_string(unsigned value);
std::string to_string(unsigned long value);
std::string to_string(unsigned long long value);
std::string to_string(float value);
std::string to_string(double value);
std::string to_string(long double value);
6.(其实和class没什么关系)
创建动态链表的时候必须要用cursor->next = new struct 来连接节点
写题时犯了zz错误先把cursor指向struct.next再进行分配。。。。结果显然分配不上去