support bazel complie this project and format code.

This commit is contained in:
zhangxing
2023-03-30 00:15:11 +08:00
committed by light-city
parent 1f86192576
commit 7529ae3a55
636 changed files with 10025 additions and 9387 deletions

View File

@@ -0,0 +1,13 @@
# please run `bazel run //practical_exercises/10_day_practice/day4/friend:class`
# please run `bazel run //practical_exercises/10_day_practice/day4/friend:func`
load("@rules_cc//cc:defs.bzl", "cc_binary")
cc_binary(
name = "class",
srcs = ["class.cpp"],
)
cc_binary(
name = "func",
srcs = ["func.cpp"],
)

View File

@@ -0,0 +1,43 @@
#include <iostream>
using namespace std;
/*
若一个类为另一个类的友元,则此类的所有成员都能访问对方类的私有成员。
声明语法将友元类名在另一个类中使用friend修饰说明。
*/
/*
如果声明B类是A类的友元B类的成员函数就可以访问A类的私有和保护数据
但A类的成员函数却不能访问B类的私有、保护数据。
*/
class A {
friend class B;
public:
void Display() { cout << x << endl; }
private:
int x;
};
class B {
public:
void Set(int i);
void Display();
private:
A a;
};
void B::Set(int i) { a.x = i; }
void B::Display() { a.Display(); }
int main(int argc, char const *argv[]) {
B b;
b.Set(10);
b.Display();
return 0;
}
/*
如果声明B类是A类的友元B类的成员函数就可以访问A类的私有和保护数据但A类的成员函数却不能访问B类的私有、保护数据
*/

View File

@@ -0,0 +1,27 @@
//使用友元函数计算两点间距离
#include <cmath>
#include <iostream>
using namespace std;
class Point {
public:
Point(int x = 0, int y = 0) : X(x), Y(y) {}
int GetX() { return X; }
int GetY() { return Y; }
friend float Distance(Point &a, Point &b);
private:
int X, Y; //私有数据成员
};
//通过将一个模块声明为另一个模块的友元,一个模块能够引用到另一个模块中本是被隐藏的信息。
float Distance(Point &a, Point &b) {
double dx = a.X - b.X;
double dy = a.Y - b.Y;
return sqrt(dx * dx + dy * dy);
}
int main() {
Point p1(3.0, 5.0), p2(4.0, 6.0);
cout << "两点距离为:" << Distance(p1, p2) << endl;
return 0;
}

View File

@@ -0,0 +1,9 @@
# 友元概念?
友元是C++提供的一种破坏数据封装和数据隐藏的机制。
通过将一个模块声明为另一个模块的友元,一个模块能够引用到另一个模块中本是被隐藏的信息。
可以使用友元函数和友元类。
为了确保数据的完整性,及数据封装与隐藏的原则,建议尽量不使用或少使用友元。
# 如何使用?
友元函数是在类声明中由关键字friend修饰说明的非成员函数在它的函数体中能够通过对象名访问 private 和 protected成员
作用:增加灵活性,使程序员可以在封装和快速性方面做合理选择。
访问对象中的成员必须通过对象名。