- 定义对象时如果没有参数,不需要加括号。
- 关于带默认值的函数:比想象中功能强大,在使用的时候同样可以带参数,但是参数必须是从左向右传递的,这样有时候只需要一个带默认值的构造函数就可以同时实现不带参数(默认)与带参数时的需求,同时也体现了函数重载的意义所在。
- 常成员:作用于对象。
- 静态数据成员:作用于类,这个类的各个对象共享,用于定义类的常数,还可用于这个类产生了多少个对象。
- 静态成员函数:类似于静态成员变量,整个类共享,几个使用注意的点详见代码2。
- 引用的新理解:在传递参数时使用引用不是将对象的所有成员穿了进去,而是通过这个“别名”访问那个对象,有点指针的感觉。
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
class Person{
public:
Person(string name,int id):_id(id){
_name = name;
numOfPerson++;
}
Person(Person &another):_id(another._id)
{
_name=another._name;
numOfPerson++;
}
~Person()
{
numOfPerson--;
}
static void getNumOfPerson()
{
cout<<numOfPerson<<endl;
}
Person(int id=0);
void output() const;
private:
string _name;
const int _id;
static int numOfPerson;
};
int Person::numOfPerson = 0;
void Person::output() const{
cout<<"name: "<<_name<<endl;
cout<<"id: "<<_id<<endl;
}
inline Person::Person(int id):_id(id)
{
_name = " ";
numOfPerson++;
}
int main()
{
int a=10;
int b=50;
const int *p;
int const *q;
int *const r=&a;
const int *const t = &a;
p=&a;
q=&a;
a=20;
p=&b;
cout<<*p<<endl<<*q<<endl<<*r<<endl;
const Person p2("Lisa",345);
string s1;
int s2;
cin>>s1>>s2;
Person person1(s1,s2),person2(person1);
person1.output();
person2.output();
person2.getNumOfPerson();
person2.~Person();
person1.getNumOfPerson();
return 0;
}
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
class Clock{
public:
Clock(int hour,string pai):_pai(pai){
_hour=hour;
numOfClock+=hour;
}
Clock(string pai=" "):_pai(pai){
_hour =3;
numOfClock+=_hour;
}
static void showNum()
{
cout<<numOfClock<<endl;
}
private:
int _hour;
const string _pai;
static int numOfClock;
};
int Clock::numOfClock = 0;
int main()
{
Clock c1(5,"sd");
c1.showNum();
Clock c2;
c2.showNum();
Clock::showNum();
return 0;
}