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 100
Explanation:
说明:
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 scope
Sample2 S;
^~~~~~~
main.cpp:13:9: error: ‘S’ was not declared in this scope
S.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:
输出:
10
Explanation:
说明:
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 ++查找字符串