C++ 基础
对C的补充
- 数据类型
bool、char、int、float、double、void、wchar_t
- 输入输出
cin >> i >> j >> k
空格表示下一个 回车表示往下运行getline(cin,s)
可用于带空格的字符串输入- 也可以用数组
cin >> a;
vector<int> arr(a);
for (int i = 0; i < a; i++) cin >> arr[i];
cout << i << j << endl
- const
- 在定义常量时和
#define
类似const float pi = 3.14
- 默认 int
- 和指针结合
const char* p = 'abcd'
指向常量的指针char* const p = 'abcd'
常指针 指针存的地址不变const char* const pc = "abcd"
- 在定义常量时和
- void 指针
void* pc
定义时不指定*(int*)pc
输出时指定
- 函数
- 匿名函数
[& = ](参数) -> 返回类型 { 函数体 }
- 内联函数
inline int func(){}
- 带默认参数的函数
void func(int x = 5, int y = 10);
- 函数重载
- 匿名函数
- 作用域标识符
::
- 强制类型转换
double(i)
(double)i
new
delete
int* p = new int(7)
int* p = new int[7]
- 引用 变量别名
int *p = &a
int &b = a
- 字符串类型
#include <string>
string str1 = "ShangHai"
string str2("dfdf")
string str3 = str1 + str2
str2 += str2
str == str1
str1[1]
面向对象
类
cpp
class 类名
{
public:
公有数据成员;
公有成员函数;
private:
私有数据成员;
私有成员函数;
protected:
保护数据成员;
保护成员函数;
};
cpp
返回类型 类名:成员函数名(参数列表)
{
函数体;
}
//内联函数:类外
inline 返回类型 类名:成员函数名(参数列表)
{
函数体;
}
访问权限
- public 都可以访问
- protected 对象不行
- private 子类也不行
对象
cpp
//1
class 类名
{
类体;
}对象名列表;
//2
类名 对象名(参数列表);//参数列表为空时,()可以不写
//3
class
{
类体;
}对象名列表;
Person p(123, "yar");//在栈上创建
Person *pp = new Person(234,"yar");//在堆上创建
构造函数
cpp
class Person
{
public:
Person(int = 0,string = "张三");
void show();
private:
int age;
string name;
};
Person::Person(int a, string s)
{
age = a;
name = s;
}
void Person::show()
{
cout << "age="<<age << endl;
cout << "name=" <<name << endl;
}
int main()
{
Person p; //0 张三
Person p2(12);//12 张三
Person p3(123, "yar");//123 yar
return 0;
}
cpp
class Person
{
public:
Person(int = 0,string = "张三");
void show();
private:
int age;
string name;
};
Person::Person(int a, string s):age(a),name(s)
{
cout << a << " " << s << endl;
}
cpp
class Person
{
public:
Person();
Person(int = 0,string = "张三");
Person(double,string);
void show();
private:
int age;
double height;
string name;
};
cpp
class Person
{
public:
Person(Person &p);//声明拷贝构造函数
Person(int = 0,string = "张三");
void show();
private:
int age;
string name;
};
Person::Person(Person &p)//定义拷贝构造函数
{
cout << "拷贝构造函数" << endl;
age = 0;
name = "ABC";
}
Person::Person(int a, string s):age(a),name(s)
{
cout << a << " " << s << endl;
}
int main()
{
Person p(123, "yar");
Person p2(p);
p2.show();
return 0;
}
析构函数
用于做一些清理工作
cpp
#include <iostream>
class String {
public:
String(const char* str) {
// 初始化字符串
}
~String() {
// 释放字符串对象所占用的内存
delete[] str_;
}
private:
char* str_;
};
int main() {
String str("Hello, World!");
std::cout << str << std::endl;
return 0;
}
对象指针
cpp
// 指向对象的指针
Person p(123, "yar");
Person* pp = &p;
Person* pp2 = new Person(234,"yar")
pp->show();
// 指向对象成员函数的指针
Person p(123, "yar");
void(Person::*pfun)();
pfun = &Person::show;
(p.*pfun)();
// this 指向调用函数的对象
class Person
{
public:
Person(int = 0,string = "张三");
void show();
private:
int age;
string name;
};
Person::Person(int a, string s):age(a),name(s)
{
}
void Person::show()
{
cout << "age="<<this->age << endl;
cout << "name=" <<this->name << endl;
}
静态成员
cpp
class Person
{
static int num;
static int plus(int a);
}
int Person::num = 7;
int Person::plus(int a)
{
cunt << a << endl;
}
友元
C++提供了友元来对私有或保护成员进行访问。友元包括友元函数和友元类
cpp
//1.将非成员函数声明为友元函数
class Person
{
public:
Person(int = 0,string = "张三");
friend void show(Person *pper);//将show声明为友元函数
private:
int age;
string name;
};
Person::Person(int a, string s):age(a),name(s)
{
cout << a << " " << s << endl;
}
void show(Person *pper)
{
cout << "age="<< pper->age << endl;
cout << "name=" << pper->name << endl;
}
int main()
{
Person *pp = new Person(234,"yar");
show(pp);
system("pause");
return 0;
}
//2.将其他类的成员函数声明为友元函数
//person中的成员函数可以访问MobilePhone中的私有成员变量
class MobilePhone;//提前声明
//声明Person类
class Person
{
public:
Person(int = 0,string = "张三");
void show(MobilePhone *mp);
private:
int age;
string name;
};
//声明MobilePhone类
class MobilePhone
{
public:
MobilePhone();
friend void Person::show(MobilePhone *mp);
private:
int year;
int memory;
string name;
};
MobilePhone::MobilePhone()
{
year = 1;
memory = 4;
name = "iphone 6s";
}
Person::Person(int a, string s):age(a),name(s)
{
cout << a << " " << s << endl;
}
void Person::show(MobilePhone *mp)
{
cout << mp->year << "年 " << mp->memory << "G " << mp->name << endl;
}
int main()
{
Person *pp = new Person(234,"yar");
MobilePhone *mp = new MobilePhone;
pp->show(mp);
system("pause");
return 0;
}
cpp
class HardDisk
{
public:
HardDisk();
friend class Computer;
private:
int capacity;
int speed;
string brand;
};
HardDisk::HardDisk():capacity(128),speed(0),brand("三星"){
}
class Computer
{
public:
Computer(HardDisk hd);
void start();
private:
string userName;
string name;
int ram;
string cpu;
int osType;
HardDisk hardDisk;
};
Computer::Computer(HardDisk hd):userName("yar"),name("YAR-PC"),ram(16),cpu("i7-4710"),osType(64)
{
cout << "正在创建computer..." << endl;
this->hardDisk = hd;
this->hardDisk.speed = 5400;
cout << "硬盘转动...speed = " << this->hardDisk.speed << "转/分钟" << endl;
}
void Computer::start()
{
cout << hardDisk.brand << " " << hardDisk.capacity << "G" << hardDisk.speed << "转/分钟" << endl;
cout << "笔记本开始运行..." << endl;
}
int main()
{
HardDisk hd;
Computer cp(hd);
cp.start();
system("pause");
return 0;
}
继承和派生
- 继承方式 私有不继承
- public 相应
- protected 转protected
- private 默认 转private
cpp
#include <iostream>
#include <string>
using namespace std;
class Person{
private:
string name;
string id_number;
int age;
public:
Person(string name1, string id_number1, int age1) {
name = name1;
id_number = id_number1;
age = age1;
}
~Person() {
}
void show() {
cout << "姓名: " << name << " 身份证号: " << id_number << " 年龄: " << age << endl;
}
};
class Student:public Person{
private:
int credit;
public:
Student(string name1, string id_number1, int age1, int credit1):Person(name1, id_number1, credit1) {
credit = credit1;
}
~Student() {
}
void show() {
Person::show();
cout << "学分: " << credit << endl;
}
};
int main() {
Student stu("白", "110103**********23", 12, 123);
stu.show();
return 0;
}
多态和虚函数
多态
编译时多态性主要是通过函数重载和运算符重载实现的;运行时多态性主要是通过虚函数来实现的
虚函数
cpp
#include <iostream>
using namespace std;
class Shape {
public:
// void draw() { cout << "Drawing a shape..." << endl; }
virtual void draw() { cout << "Drawing a shape..." << endl; }
};
class Circle : public Shape {
public:
void draw() { cout << "Drawing a circle..." << endl; }
};
int main() {
Shape* a1 = new Circle();
Circle* a2 = new Circle();
a1->draw();
a2->draw();
return 0;
}
纯虚函数 virtual int func(int a) = 0;
抽象类
至少有一个纯虚函数,那么就称该类为抽象类
运算符重载
cpp
class MyString {
public:
MyString(const std::string& str) : str_(str) {}
MyString& operator+(const MyString& other) const {
MyString result(str_ + other.str_);
return result;
}
std::string str_;
};
int main() {
MyString s1("Hello");
MyString s2("World");
MyString s3 = s1 + s2;
std::cout << s3.str_ << std::endl;
return 0;
}
IO和文件
IO流
iostream
文件流
fstream
cpp
int main() {
ofstream fout("../test.txt", ios::out);
if (!fout) {
cout << "Cannot open output file." << endl;
exit(1);
}
fout << "I am a student.";
fout.close();
return 0;
}
int main() {
ifstream fin("../test.txt", ios::in);
if (!fin) {
cout << "Cannot open output file." << endl;
exit(1);
}
char str[80];
fin.getline(str , 80);
cout << str <<endl;
fin.close();
return 0;
}
cpp
#include <iostream>
#include <fstream>
using namespace std;
struct list{
char course[15];
int score;
};
int main() {
list ob[2] = {"Computer", 90, "History", 99};
ofstream out("test.txt", ios::binary);
if (!out) {
cout << "Cannot open output file.\n";
abort(); //退出程序,作用与exit相同。
}
for (int i = 0; i < 2; i++) {
out.write((char*) &ob[i], sizeof(ob[i]));
}
out.close();
return 0;
}
int main() {
list ob[2];
ifstream in("test.txt", ios::binary);
if (!in) {
cout << "Cannot open input file.\n";
abort();
}
for (int i = 0; i < 2; i++) {
in.read((char *) &ob[i], sizeof(ob[i]));
cout << ob[i].course << " " << ob[i].score << endl;
}
in.close();
return 0;
}
// eof()检测是否到文件尾
泛型和模板
函数模板
用于适应不同的参数类型
cpp
#include <iostream>
using namespace std;
template <class Type>
Type Max(Type x, Type y) {
return x > y ? x : y;
}
template <class Type>
Type Max(Type x, Type y, Type z) {
Type t = x > y ? x : y;
t = t > z ? t : z;
return t;
}
int main() {
cout << "33,66中最大值为 " << Max(33, 66) << endl;
cout << "33,66,44中最大值为 " << Max(33, 66, 44) << endl;
return 0;
}
类模板
cpp
#include <iostream>
template<typename T>
class Vector {
public:
Vector() : x_(0), y_(0) {}
Vector(T x, T y) : x_(x), y_(y) {}
T& x() { return x_; }
T& y() { return y_; }
T x() const { return x_; }
T y() const { return y_; }
private:
T x_;
T y_;
};
int main() {
Vector<int> v1(10, 20);
Vector<float> v2(3.0f, 4.0f);
std::cout << "v1: (" << v1.x() << ", " << v1.y() << ")" << std::endl;
std::cout << "v2: (" << v2.x() << ", " << v2.y() << ")" << std::endl;
return 0;
}
其它
异常处理
cpp
#include <iostream>
void try-catch(int x) {
try {
if (x < 0) {
throw runtime_error("Negative number!");
}
cout << x << endl;
} catch (const runtime_error& e) {
cout << "Error: " << e.what() << endl;
}
}
int main() {
try-catch(10);
try-catch(-10);
return 0;
}
命名空间
using namespace std;
std::cout