1.声明类
公有属性: public
私有属性: private
保护属性: protected
class 类名{
属性: 类型 变量名;
...
};//私有成员不能在类外部被操作
2.模板类
template <class 数据类型>
class 模板类名{
属性: 类型 变量名;
...
属性 类型 函数名(){
...
}
};//当方法为公有属性public时,属性可忽略不写
3.重载运算符
类名 类名::operator 重载符号(操作类型){
类名 temp = *this;//返回当前对象副本
...
return temp;
}//类中用法
类型 operator 重载符号(double s,Book b)
{
return s+b.Price;
}//对于结构体类型用法
ostream& operator<<(ostream &Output,Dialog &B){
Output<<d.Length<<","<<d.Width<<","<<d.Color;
return Output;
}//重载输出流函数示例
4.异常处理机制
try{
...//可能出现异常的代码
throw(异常返回值);
}catch(异常返回类型){
...
}
5.操作空间
new 类型[大小];//申请空间
delete 变量名;//清除空间
6.转换构造函数
类名(转换对象类型 变量名){
...
}
//构造函数不能声明为虚构造函数,即不能用virtual修饰。
class MyClass {
private:
int value;
public:
// 默认构造函数
MyClass(int v) : value(v) {
cout << "Constructor called, value = " << value << endl;
}
// 拷贝构造函数
MyClass(const MyClass& other) {
value = other.value;
cout << "Copy Constructor called, value = " << value << endl;
}