ICPC笔记
Class基础
Class基础 1. 基本操作 2. 初始化 3. new与delete 4. 运算符重载 5. this指针 6. nullptr 7. 自增,左值运算 8. 友元函数 一、基本结构 二、private , public , protected 1. private 私有部分, 类外不能直接访问...
Class基础
- 基本操作
- 初始化
new与delete- 运算符重载
- this指针
- nullptr
- 自增,左值运算
- 友元函数
一、基本结构
class 类名 {
private:
// 私有成员变量
public:
// 公有成员函数
};
二、private , public , protected
1. private
私有部分,类外不能直接访问。
class Student {
private:
int age;
};
int main() {
Student s;
s.age = 18; // 错误!age 是 private
}
2. public
公有部分,类外可以访问。
class Student {
public:
int age;
};
int main() {
Student s;
s.age = 18; // 可以
}
但一般不建议直接把数据成员写成 public,更推荐:
private:
int age;
public:
void setAge(int a);
int getAge();
也就是:数据藏起来,通过函数操作。
3. protected
protected 最主要用于继承。
class Vehicle {
protected:
string brand;
int year;
};
class Car : public Vehicle {
public:
void setInfo(string b, int y) {
brand = b; // 可以,子类能访问 protected
year = y; // 可以
}
};
int main() {
Car c;
c.brand = "BYD"; // 错误,类外不能访问 protected
}
protected 可以理解为:
对外隐藏,但允许儿子类使用。
三、基本构造函数
构造函数是:创建对象时自动调用的函数。
1.默认构造函数
没有参数的构造函数叫默认构造函数
class Student {
private:
string name;
int age;
public:
Student() {
name = "unknown";
age = 0;
}
void show() const {
cout << name << " " << age << endl;
}
};
2.带参构造函数
带参构造函数就是创建对象时传入初始值
class Student {
private:
string name;
int age;
public:
Student(string n, int a) {
name = n;
age = a;
}
};
四、成员函数
可以在类内声明实现
或者在类内声明,类外实现
类里面只写声明:
class Student {
private:
string name;
int age;
public:
Student(string n, int a);
void showInfo();
};
类外写实现:
Student::Student(string n, int a) : name(n), age(a) {}
void Student::showInfo() {
cout << name << " " << age << endl;
}
这里的 Student:: 表示:
这个函数属于 Student 类。
完整写法:
#include <iostream>
#include <string>
using namespace std;
class Student {
private:
string name;
int age;
public:
Student(string n, int a);
void showInfo();
};
Student::Student(string n, int a) : name(n), age(a) {}
void Student::showInfo() {
cout << name << " " << age << endl;
}
int main() {
Student s("李四", 20);
s.showInfo();
return 0;
}
const 成员函数
比如:
void print() const;
后面的 const 表示:
这个函数不会修改对象内部的数据成员。
例如:
void Point::print() const {
cout << x << " " << y << endl;
}
在 print() 里面不能写:
x = 10; // 错误,因为 print 是 const 成员函数
一般来说,像 getAge()、print()、showInfo() 这种只看不改的函数,都可以加 const。