目录
1) Class without pointer member(s) ——不带指针成员的类
2)Class with pointer member(s) —— 带指针成员的类
三、Obeject Based(基于对象) vs. Object Oriented(面向对象)
一、C Vs C++ (在数据与函数上角色的不同作比较)
C语言设计程序的时候,会准备一些数据、一些函数(函数用于处理数据)。
这里的数据代表某一些类型,根据类型去创建一些真正的数据变量出来,函数的功能就是去处理这些数据变量。
缺点:由于语言没有提供一些关键字,所以这些数据变量一定是全局的,因此各个函数都可以去处理他们。
C++语言中在设计程序的时候,将数据和处理相关数据的函数包在一起(就是class,可以理解为之前C中的struct)。
这些数据只能由这些函数来处理,其他不会看到,不会混杂在一起、
C++提供了更多的关键字去操作更多的特性。C++中也有strcut结构类型,几乎等同于class(微小差别)。
将数据和函数包在一起(class)的形式去创建出很多很多对象。
二、C++ 关于数据和函数
分为带指针成员的类以及不带成员指针的类,他们new的方式及后续处理方式都不尽相同(后话)
1) Class without pointer member(s) ——不带指针成员的类
以较为经典的“复数"为例:
complex c1(2, 1);
complex c2;
complex *pc = new complex(0, 1);
2)Class with pointer member(s) —— 带指针成员的类
以经典的”字符串“为例:
string s1("Hello ");
string s2("World ");
string* ps = new string;
三、Obeject Based(基于对象) vs. Object Oriented(面向对象)
Object Based: 面对的是单一class的设计
Object Oriented:面对的是多重classes的设计, class和class之间的关系
四、第一个C++程序
一)classes 的 两个经典分类
带指针成员的类、不带指针成员的类
二)C++ Programs 代码基本形式
延伸文件名(extension file name)不一定是".h"或”.cpp“,也可能是.hpp或者其他或者甚至没有延展名。
三)输出 Output, C++ vs. C
1) C++
#include<iostream>
using namespace std;
int main()
{
int i = 7;
cout << "i = " << i << endl;
return 0;
}
2)C
#include <cstdio>
int main()
{
int i = 7;
printf("i = %d \n", i);
return 0;
}
四)头文件中的防卫式声明
1) complex.h
#ifndef COMPLEX
#define COMPLEX
//***
#endif
2)complex-test.h
#include <iostream>
#include "complex.h“
using namespace std;
int main()
{
complex c1(2,1);
complex c2;
cout << c1 << endl;
cout << c2 << endl;
c2 = c1 + 5;
c2 = 7 + c1;
c2 = c1 + c2;
c2 += c1;
c2 += 3;
c2 = -c1;
cout << (c1 == c2) << endl;
cout << (c1 != c2) << endl;
cout << conj(c1) << endl;
return 0;
}
五)头文件的布局
六)class的声明
class complex //class head
{// class body
public:
complex(double r = 0, double i = 0)
: re(r), im(i)
{ }
complex & operator += (const complex &);
//有些函数在此定义,另一些在body之外定义
double real() const { return re; }
double imag() const { return im; }
private:
double re, im;
friend complex& __doap1 (complex*, const complex &);
}
{
complex c1(2, 1);
complex c2;
// ...
}
七)类模板简介(class template)
template<typename T>
class complex //class head
{// class body
public:
complex(double r = 0, double i = 0)
: re(r), im(i)
{ }
complex & operator += (const complex &);
//有些函数在此定义,另一些在body之外定义
T real() const { return re; }
Timag() const { return im; }
private:
T re, im;
friend complex& __doap1 (complex*, const complex &);
}
{
complex<double> c1(2.5, 1.5);
complex<int> c2(1,2);
// ...
}