当前位置:网站首页>Chapter 7 class
Chapter 7 class
2022-04-21 15:28:00 【(ಠ . ̫.̫ ಠ)】
List of articles
Preface
This paper introduces the basic content of class .
chapter 7 class
#include <iostream>
#include <string>
using std::istream;
using std::ostream;
using std::string;
class Sales_data{
// Friend reputation , Not a function name , The function can be defined at the same time as the friend's name , It must also be stated that
friend Sales_data add(const Sales_data&, const Sales_data&);
friend istream & read(istream&, Sales_data&);
friend ostream & print(ostream&, const Sales_data&);
public:
// New constructor
Sales_data() = default;
Sales_data(const string &s):bookNo(s){
}
Sales_data(const string &s, unsigned n, double p):
bookNo(s), units_sold(n), revenue(p*n) {
}
// Constructor internal name , External definition
Sales_data(istream&is);
// Member functions , Fame must be inside , Definition does not require
// Defined inside the class , implicit inline function
// The compiler processes classes in two steps :1. Compiler member name 2. Member function body
string isbn() const {
return bookNo;}
Sales_data& combine(const Sales_data&) ; // Constant member functions
private:
double avg_price() const;
// Data member
string bookNo;
unsigned int units_sold = 0;
double revenue = 0;
};
// Nonmember interface function , The name should be in the same header file as the class
Sales_data add(const Sales_data&, const Sales_data&);
ostream &print(ostream&, const Sales_data&);
istream &read(istream&, Sales_data&);
// Member functions defined outside the class
double Sales_data::avg_price() const{
if (units_sold){
return revenue / units_sold;
}else{
return 0;
}
}
Sales_data& Sales_data::combine(const Sales_data&rhs){
units_sold += rhs.units_sold;
revenue += rhs.revenue;
return *this;
}
// Nonmember interface function Definition
istream & read(istream&is, Sales_data&item){
double price = 0;
is >> item.bookNo >> item.units_sold >> price;
item.revenue = price * item.units_sold;
return is;
}
// IO Class cannot be copied
ostream & print(ostream&os, const Sales_data&item){
os << item.isbn() << " " << item.units_sold << " "
<< item.revenue << " " << item.avg_price();
return os;
}
Sales_data add(const Sales_data&item1, const Sales_data&item2){
Sales_data sum = item1; // Copy the object of the class
return sum.combine(item2);
}
// Constructor internal name , External definition
// Constructor has no return type
// Because the function name is the same as the class name , So it's a constructor
Sales_data::Sales_data(istream &is){
read(is, *this); //read, from is Read a transaction information in the and
// Deposit in this In the object
}
int main(){
Sales_data total;
if (read(cin, total)){
Sales_data trans;
while (read(cin, trans)){
if (total.isbn() == trans.isbn()){
total.combine(trans);
}else{
print(cout, total) << endl;
total = trans;
}
}
print(cout, total) << endl;
}else{
cout << "No data?!" << endl;
}
// Sales_data item1 = {"jskf", 4, 89};
// print(cout, item1) << endl;
}
Constructors
amount to __init__,
Constructor initializer list
// Constructor initializer list
Sales_data(const std::string&s, unsigned n, double p):
bookNo(s), units_sold(n), revenue(p*n) {
}
// : bookNo(s), units_sold(n), revenue(p*n) be called Constructor initializer list
this The type of is a constant pointer to the non constant version of the class type , The object it points to is an extraordinary quantity . Add... After the formal parameter list const representative this It points to a constant .
The initial value in the class must be expressed with the symbol = Or curly brackets .
The name and definition of the class
Class must be fully defined when the object of the class is created , After the class name, there can be a pointer or reference to the class
class Y;
class X{
public:
Y *haha;
};
class Y{
public:
X haha;
};
friend When you can, the function 、 class 、 class
Friends are not transitive

Friends only affect function permissions
7.3.4 I'm going to practice on this day
class WindowMgr{
private:
std::vector<Screen> screens{
Screen(24, 80, ' ')};
public:
void clear(Screen &);
};
class Screen{
friend void WindowMgr::clear(Screen &);
public:
using pos = std::string::size_type;
// typedef std::string::size_type pos;
Screen(/* args */)=default;
// ~Screen();
Screen(pos a, pos b, char c):
contents(a*b, c), height(a), width(b){
}
// Screen &display(ostream&) const;
//Screen &display(ostream &os){do_display(os); return *this;}
//const Screen &display(ostream &os) const{do_display(os); return *this;}
private:
string contents;
pos cursor = 0, height = 0, width = 0;
/*void do_display(ostream &os) const{ for (int i=0;i<height; ++i){ for (int j=0;j < width; ++j){ os << contents[j + i*width]; } os << '\n'; } }*/
};
Screen &clear(Screen &scrn){
string temp(scrn.width*scrn.height, ' ');
scrn.contents = temp; // Why? scrn.contents = " " No way. ??
return scrn;
}
constructor
Constructors :
// initialization
Sales_data::Sales_data(const string &s, unsigned cnt, double price):
bookNo(s), units_sold(cnt), revenue(cnt * price){
}
// assignment
Sales_data::Sales_data(const string &s, unsigned cnt, double price){
bookNo = s; units_sold = cnt; revenue = cnt * price;
}
Initialization operation is different from assignment operation
- If the member is const Or quote , Must be initialized
The member initialization order of the class is independent of the order of the constructor initializer list , In the order defined in the class
It is best to keep the order of constructor initializers consistent with the order of member names . And if possible , Try to avoid initializing other members with some members .
Default arguments and constructors
Delegate constructor
class Sales_data{
public:
Sales_data(std::string s, unsigned cnt, double price):
bookNo(s), units_sold(cnt), revenue(cnt*preice){
}
Sales_data():Ssles_data("", 0, 0) {
}
Sales_data(std::string s):Sales_data(s, 0, 0) {
}
Sales_data(std::istream &is):Sales_data() {
read(is, *this);}
};
Implicit class type conversion
// Only one step
string s = "abc";
item.combine(s); //
item.combine(Salse_data("abc")); //
item.combine(string("abc")) ; //
item.combine("abc"); //
// Automatic implicit class type conversion
// explicit Keywords are only allowed in constructor names within a class
explicit Sales_data(const std::string &s):bookNo(s){
}
item.combine(s); //
Sales_data item1(null_book); // Direct initialization
Sales_data item2 = null_book; // Can't be explicit Constructor is used for the initialization process in copy form
// Explicit cast
Aggregate class
The disadvantages are obvious , Not recommended
struct Data{
int ival;
string s;
};
Data val1 = {
0, "Anna"}; // The order must be consistent
Literal constant class
Static member of class
Name static member
You need to define... Outside the class
( It's kind of like python Class properties in )
class Account{
public:
void calculate() {
amount += amount * interestRate;}
// static Keywords can only appear within a class
static double rate() {
return interestRate;}
static void rate(double);
private:
std::string owner;
double amount;
static double interestRate;
static double initRate();
};
// Use static members of the class
double r;
r = Account::rate();
Account ac1, *ac2 = &ac1;
r = ac1.rate();
r = ac2 -> rate (); //emm As expected and python equally
版权声明
本文为[(ಠ . ̫.̫ ಠ)]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204211516357649.html
边栏推荐
- 111页精细化工股份公司数据字转型解决方案
- APP评测的网站有哪些?
- 什么是电子邮箱地址?好用的电子邮箱注册申请
- Login refactoring notes
- AcWing 1866. 围栏刷漆(区间求交)
- 机器学习方法创建可学习的化学语法,构建可合成的单体和聚合物
- [机器学习导论]——第六课——贝叶斯分类器
- 读书破万“卷”:国民阅读洞察2022
- [binary search - simple] sword finger offer II 072 take a square root
- [Unity] error CS0433: The type ‘Task‘ exists in both Unity. Tasks,....
猜你喜欢

汉诺塔游戏与递归

Use konvajs three steps to realize a small ball game

OpenHarmony3. 1 H264 video playback Road

Embedded development: three skills of reusing development board for testing

返璞归真,多方安全计算要回归到“安全”的本源考虑
![[advanced C language] user defined type: struct, bit segment, enumeration, union](/img/c5/4f2756aaa642a17c322ea480987041.png)
[advanced C language] user defined type: struct, bit segment, enumeration, union

Hand in hand to teach you to realize hand-painted style graphics

Spark / Scala - read rcfile & orcfile

智慧工地综合解决方案

小程序简介和开发工具
随机推荐
72页互联网智慧园区解决方案
智慧园区数融通-数字化赋能运营管理平台解决方案
小程序简介和开发工具
【二分搜索-中等】1498. 满足条件的子序列数目
[binary search - simple] 441 Arrange coins
EmlParse:一款超轻量级的批量解析EML格式电子邮件的工具
JD cloud has launched cloud computing to create an unbounded office experience for the future
OpenLayers入门(一)
【unity笔记】L2Unity Shader基础
Betterscroll source code, reading and learning typescript
JDBC和数据库连接池
How do I log in to the enterprise mailbox? Enterprise mailbox login method
OpenLayers入门(二)
Embedded development: three skills of reusing development board for testing
[binary search - medium] 1855 Maximum distance of subscript alignment (need to review double pointer method)
什么是电子邮箱地址?好用的电子邮箱注册申请
【unity笔记】L3Unity Shader学习开始
AcWing 1788. Why do cows cross the road (simulation)
嵌入式驱动模块的加载与卸载
使用konvajs三步实现一个小球游戏