类的设计尽可能将 共有接口与实现细节分开。(实现对数据的隐藏)即OOP面向对象的形式。
类与结构,类默认的成员为private,结构体默认的成员为public
PS:基本上都是显式调用。
1、类成员函数
有两个特征:
a:定义成员函数时,使用作用域解析运算符(::)来标识函数所属的类
b:类的方法(函数)可以访问private 组件
class mywork
{
private:
int a=0;
int b=100;
public:
int getA();
void setA(int a);
}
;
int mywork::getA()//就是a的描述
{
return a;}
void mywork::setA(int tmp)
{ a=tmp;//为b的描述
}
2、类的基础设计格式
class clasname{
private:
data member declarations; //数据申明;内联函数等
public:
member function prototypes;//成员函数原型,
};
3、类的构造函数和析构函数
前言:类让数据成为 公有,违反了 c++ 类(数据隐藏)的初衷。
当调用 未被显示初始化类对象时,总是调用默认的构造函数:
AA:构造函数
构造函数:创建类的时候,对其进行初始化(数据成员);名称与类名相同,
没有申明类型
构造函数的参数不能为 成员变量的变量名;为避免混乱.
A:在数据成员名中使用m_前缀。//eg:int m_tatol;
B:成员名使用_后缀。 //eg:int tatol_;
stock garment("jack",50,2.5);//隐式调用构造函数
stock garment=stock("jack",50,2.5);//显式调用构造函数
eg:
.h
class stock
{
private:
//stock(const std::string& co, long n, double pr);
std::string company;
long shares;
double share_val;
double total_val;
void set_tot() { total_val = shares * share_val; }
public:
void acquire(const std::string& co, long n, double pr);
int getPrice();
};
.cpp
void stock::acquire(const std::string& co, long n, double pr)
{
company = co;
shares = n;
share_val = pr;
set_tot;
}
int stock::getPrice()
{
return total_val;
}
.cpp 实现文件中
stock a;//这个时候 就会调用默认的构造函数,原型+实现为
stock::stock(){};不会执行任何程序(没有初始化 数据变量)
禁止创建未初始化的对象,然而,如果创建对象,而不显式的初始化,则必须默认的构造函数 如上。
构造函数两种方式;
1 、test::test(const std::string& co, long n, double pr){};
2、默认的方式; test:test(){
company=“no”;shares=0;share_val=0.0;total=0.0;//重载
}stock first(“name”); //call 构造函数
stock second();//申明 一个功能
stock thrid;// call 构造函数。
应该避免第二种写法,它并不会调用构造函数。
BB: 析构函数
作用:用于释放内存,
1、如果没有 new ,就可以 做一个隐式的析构函数,(什么都不添加);
2、如果有,则需要显式申明和调用 析构函数。
~stock();
什么时候被调用,通常不应再代码中调用析构函数。
1、如果创建的是静态存储类对象,则其析构函数在程序结束时被调用
全局变量(见之前的内存模型),static int a;extern int a;int a;放在类的外面的
2、创建的是自动存储类对象,在完成代码块的时候被调用,eg:临时变量
3、通过new动态创建的,仅当调用 delete的时候,析构函数被调用。
4、this指针
#pragma once
#include <iostream>
class stock
{
private:
std::string company;
long shares;
double share_val;
double total_val;
void set_tot() { total_val = shares * share_val; }
public:
stock(const std::string& co, long n, double pr);
void acquire(const std::string& co, long n, double pr);
int getPrice();
const double getTotal(){ return total_val;}//限定了 total_val为只读
const stock &topval(const stock&s) const;
//隐式访问一个对象,显示访问另一个对象,返回其中对象的引用
//第一个const;返回一个只读的stock 对象的引用;
//第二个const;只读模式调用stock对象
//第三个const;表明该函数不能被隐式 访问
};
const stock&stock::topval(const stock &s) const
{
if (s.total_val > total_val)
{
return s;
}
else
return *this;
//this 指向用来 调用成员函数 的对象(隐藏参数的传递方法)
//eg: stock1.topval(stock2) this=stock1对象的地址
//
}
5、类的作用域
类数据成员和类函数名的作用域为整个类;对类外是为未知的;访问类的成员,必须通过对象。
- 作用域为类的常量
eg: class test
{private:
const int months=12;
double costs[months];
};//这样的做法不可行;
c++提供了成员初始化,但不适用于前述数组申明。
替代方法:
a ;采用枚举
在类中申明枚举,作用域为整个类。
class test
{private:
enum{months=12};
double costs[months];
};
b;使用关键字 static
class test
{private:
static const int months=12;
double costs[months];
};
枚举的新写法;enum class egg{small,large};//避免了枚举量名 发生冲突;