1,类的定义和使用
2,源码
#include <iostream>
#include <string>
/*
1,public: 类的所有对象都可以调用public内声明的函数和变量
2,private: 只能被类的成员函数调用,不能被类的对象调用
3,友元函数: 声明后在函数内允许类对象调用使用私有变量
4,类函数实现中::使用,作用域运算符来说明,我们定义了一个类函数,该函数在类内声明
5,构造函数: 构造函数和类的名字相同,没有返回类型;根据参数的不同类可以有多个构造函数(函数重载)
6,默认构造函数:如果程序没有显示的定义构造函数,编译器会为我们隐式定义一个默认构造函数
7,类的拷贝赋值:在使用类的拷贝和赋值过程中需要特别小心,有可能会出错
*/
using namespace std;
//类的定义
class Sales_Data
{
public:
Sales_Data(); //构造函数
Sales_Data(string init_str);
void Sales_Print(void); //公共函数
friend void User_Print(Sales_Data sales_data); //友元函数
private:
string str; //私有变量
void Salse_Input(void); //私有函数
};
//类成员函数实现
void Sales_Data::Sales_Print(void)
{
cout << str <<endl;
}
void Sales_Data::Salse_Input()
{
str = "hello world";
}
//类构造函数
Sales_Data::Sales_Data()
{
str = "";
}
Sales_Data::Sales_Data(string init_str)
{
str = init_str;
}
/*类的相关非成员函数,被声明友元函数可以调用类的私有变量*/
void User_Print(Sales_Data sales_data)
{
sales_data.Salse_Input();
cout << sales_data.str <<endl;
}
int main(void)
{
Sales_Data sales_data;
Sales_Data sales_data1("good day!");
//sales_data.Salse_Input(); 错误使用,类对象不能调用类私有成员函数
sales_data.Sales_Print();
sales_data1.Sales_Print();
User_Print(sales_data);
return 0;
}
#include <iostream>
#include <string>
using namespace std;
/*
1,定义类型成员:例:定义pos为size_type类型和 using pos = std::string::size_type相同
2,引用:格式:类型 &引用变量名 = 已定义变量名;特点:一个变量可以取多个别名、引用必须初始化、引用只能引用
一次;常用作函数参数,函数返回值
3,引用作为函数返回值:1,不使用引用作为函数返回值:返回值是调用函数时创建的临时对象,函数调用完成后释放
2,使用引用作为函数返回值:返回的是对象本身,所以千万不能返回局部对象的引用
3,引用作为函数返回值,返回时不能做算术运算
4,const修饰引用作为函数返回值,防止被莫名其妙复制
4,类内联函数:定义在类内部的函数自动是inline的
5,类成员函数可以重载
6,类的声明
7,友元类
8,类的静态成员
*/
class Screen; //类的声明
class Screen //类的定义
{
public:
typedef std::string::size_type pos;
Screen() = default; //使用default生成默认构造函数
Screen(pos ht, pos wt, char c); //另外一个构造函数,可以让用户进行屏幕初始化
pos get_cursor() //隐式内联函数,在类内定义函数
{
return cursor;
}
inline string get_contens(); //显示内联函数
void set_ht_wt(pos ht); //类成员函数重载
void set_ht_wt(pos ht, pos wt);
Screen &get_this(); //返回对象,通过引用返回的是对象本身不是对象副本
friend class Max_Screen; //友元类,Max_Screen可以调用Screen的函数和变量
static void Screen_Init(void); //类的静态成员函数
private:
pos cursor = 0;
pos height = 0, weight = 0;
std::string contens;
};
//重载构造函数
Screen::Screen(pos ht, pos wt, char c)
{
cursor = c;
height = ht;
weight = wt;
cout <<"Init ht wt:";
cout << ht << " ";
cout << wt <<endl;
}
//类函数定义
string Screen::get_contens()
{
return contens;
}
//类成员函数重载
void Screen::set_ht_wt(pos ht)
{
height = ht;
}
void Screen::set_ht_wt(pos ht, pos wt)
{
height = ht;
weight = wt;
cout << "Set ht wt:";
cout << ht << " "<< wt <<endl;
}
//返回对象this指针
Screen &Screen::get_this()
{
return *this;
}
//友元类
class Max_Screen
{
public:
private:
};
//类静态成员函数
void Screen::Screen_Init()
{
//静态成员函数不能调用私有变量等
// cursor = 0;
// weight = 0;
// height = 0;
cout << "Screen Init" <<endl;
}
int main()
{
//引用测试
int a = 1, &a1 = a;
a1++;
cout << a <<endl;
//静态成员函数测试
Screen::Screen_Init();
//类测试
Screen screen(100, 20, 10);
screen.set_ht_wt(200, 200);
//静态成员测试,可以被类对象调用
screen.Screen_Init();
return 0;
}