c ++查找字符串_C ++朋友功能| 查找输出程序| 套装2
c ++查找字符串
Program 1:
程序1:
#include <iostream> using namespace std;class Sample1 {int A, B;friend class Sample2; };class Sample2 {int X, Y;public:Sample2(){X = 5;Y = 5;}void fun(){Sample1 S;S.A = 10 * X;S.B = 20 * Y;cout << S.A << " " << S.B << endl;} };int main() {Sample2 S;S.fun();return 0; }Output:
輸出:
50 100Explanation:
說明:
Here, we created two classes Sample1 and Sample2, we made Sample2 class as a friend of Sample1 class. Then Sample2 can access the private members of Sample1.
在這里,我們創建了兩個類樣本1和樣本2,我們做了樣品2類作為樣本1類的朋友。 然后Sample2可以訪問Sample1的私有成員。
Here, we access the private members A and B of Sample1 class in the member function fun() of Sample2 class and then we set the value to the members and print values.
在這里,我們訪問Sample2類的成員函數fun()中Sample1類的私有成員A和B ,然后將值設置為成員并打印值。
Program 2:
程式2:
#include <iostream> using namespace std;class Sample1 {int A, B;public:friend class Sample2;void fun1(){Sample2 S;S.X = 10;S.Y = 20;cout << S.X << " " << S.Y << endl;} };class Sample2 {int X, Y;public:friend class Sample1;Sample2(){X = 5;Y = 5;}void fun2(){Sample1 S;S.A = 10 * X;S.B = 20 * Y;cout << S.A << " " << S.B << endl;} };int main() {Sample2 S;S.fun();return 0; }Output:
輸出:
main.cpp: In member function ‘void Sample1::fun1()’: main.cpp:12:9: error: ‘Sample2’ was not declared in this scopeSample2 S;^~~~~~~ main.cpp:13:9: error: ‘S’ was not declared in this scopeS.X = 10;^ main.cpp: In function ‘int main()’: main.cpp:43:7: error: ‘class Sample2’ has no member named ‘fun’; did you mean ‘fun2’?S.fun();^~~Explanation:
說明:
It will generate an error because we are accessing the Sample2 from Sample1 but Sample2 is declared below, so it is not accessible. Then it will generate an error.
因為我們訪問來自樣本1的樣品2,但樣品2如下聲明,所以它不能訪問它會產生一個錯誤。 然后它將產生一個錯誤。
Program 3:
程式3:
#include <iostream>class SampleB;class SampleA { public:void show(SampleB&); };class SampleB { private:int VAL;public:SampleB() { VAL = 10; }friend void SampleA::show(SampleB& x); };void SampleA::show(SampleB& B) {std::cout << B.VAL; }int main() {SampleA A;SampleB OB;A.show(OB);return 0; }Output:
輸出:
10Explanation:
說明:
Here, we create two classes SampleA and SampleB. ?And, we created show() function as a friend of SampleB, then it can access private members of class SampleB.
在這里,我們創建兩個類SampleA和SampleB 。 并且,我們以SampleB的朋友的身份創建了show()函數,然后它可以訪問SampleB類的私有成員。
Then, we defined show() function, where we accessed private member VAL inside function show() of SampleA class and print the value VAL.
然后,我們定義了show()函數,在此我們訪問SampleA類的函數show()內部的私有成員VAL并打印值VAL 。
翻譯自: https://www.includehelp.com/cpp-tutorial/friend-function-find-output-programs-set-2.aspx
c ++查找字符串
總結
以上是生活随笔為你收集整理的c ++查找字符串_C ++朋友功能| 查找输出程序| 套装2的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python 程序耗时记录_Python
- 下一篇: 为什么wait和notify必须放在sy