class Car
{
private: //只允許類的成員函數訪問
int num;
public: //程序的任意函數均可訪問
char * name;
protected: //對於派生類來說是公有的,對於程序的其他部分來說是私有的
int price;
};
#include<iostream>
using namespace std;
class Car
{
public:
static int n;
void counter();
};
<span style="color:#ff0000;">int Car::n = 0; </span> //靜態成員的初始化,不可在類內直接初始化,否則會報錯
void Car::counter()
{
n++;
}
int main(void)
{
Car car1;
car1.counter();
cout<<"static n = "<<Car::n<<endl;
Car car2;
car2.counter();
Car car3;
car3.counter();
cout<<"static n = "<<Car::n<<endl;
return 0;
}
/*
結果:
static n = 1
static n = 3
*/
#include<iostream>
using namespace std;
class Student
{
public:
int math;
int english;
int biology;
Student(int math = 1,int english = 1,int biology = 1); //這裏構造函數的默認初始值爲1
void display() //類體內定義函數
{
cout<<"Math = "<<math<<",English = "<<english<<",Biology = "<<biology<<endl;
}
};
Student::Student(int m,int e,int b) //類體外定義構造函數,構造函數必須與類名相同
{
math = m;
english = e;
biology = b;
}
int main(void)
{
Student stu1;
stu1.display();
Student stu2(100,80,95);
stu2.display();
return 0;
}
/*
運行結果:
Math = 1, English = 1, Biology = 1
Math = 100,English = 80,Biology = 95
*/
#include<iostream>
using namespace std;
class Student
{
public:
int a;
int b;
Student(Student &stu);
Student(int aa,int bb);
void show()
{
cout<<"a = "<<a<<", b = "<<b<<endl;
}
};
Student::Student(Student &stu)
{
a = stu.a+10;
b = stu.b+20;
}
Student::Student(int aa,int bb)
{
a = aa;
b = bb;
}
int main(void)
{
Student stu1(1,2);
stu1.show();
Student stu2(stu1);
stu2.show();
return 0;
}
/*
運行結果:
a = 1, b = 2
a = 11, b = 22
*/
析構函數
#include<iostream>
using namespace std;
class Car
{
int n;
public:
Car(int nn); //構造函數
~Car(); //析構函數
void display()
{
cout<<"Buding...."<<endl<<endl;
cout<<"n = "<<n<<endl<<endl;
}
};
Car::Car(int nn)
{
n = nn;
}
Car::~Car() //析構函數類體外定義
{
cout<<"Releasing...."<<endl;
}
int main(void)
{
Car car1(100);
car1.display();
return 0;
}
/*
運行結果:
Buding....
n = 100
Releasing....
*/
this指針