C朋友班和朋友会员功能
我正在学习C类中的朋友函数,朋友类和朋友成员函数;
现在,以下代码编译正常: #include <iostream> class A { public: friend class B; //friend void B::set(int i); //friend int B::get(); friend int function(A a); A(int i); void set(int i); int get(); private: int i; }; A::A(int i) : i(i) { } void A::set(int i) { this->i = i; } int A::get() { return i; } class B { public: B(A a); void set(int i); int get(); private: A a; }; B::B(A a) : a(a) { } void B::set(int i) { a.i = i; } int B::get() { return a.i; } int function(A a); int main(int argc,char *argv[]) { A a(0); std::cout << "in A i=" << a.get() << std::endl; a.set(10); std::cout << "in A i=" << a.get() << std::endl; B b(a); std::cout << "in B i=" << b.get() << std::endl; b.set(21); std::cout << "in B i=" << b.get() << std::endl; std::cout << "function returns " << function(a) << std::endl; } int function(A a) { return a.i; } 我能够给B级友谊并在A类中起作用“功能”,而无需前进声明B类或功能“功能”. #include <iostream> class B; // doesn't work,incomplete type (complete type needed) class A { public: //friend class B; friend void B::set(int i); friend int B::get(); friend int function(A a); A(int i); void set(int i); int get(); private: int i; }; A::A(int i) : i(i) { } void A::set(int i) { this->i = i; } int A::get() { return i; } B::B(A a) : a(a) { } void B::set(int i) { a.i = i; } int B::get() { return a.i; } int function(A a); int main(int argc,char *argv[]) { A a(0); std::cout << "in A i=" << a.get() << std::endl; a.set(10); std::cout << "in A i=" << a.get() << std::endl; B b(a); std::cout << "in B i=" << b.get() << std::endl; b.set(21); std::cout << "in B i=" << b.get() << std::endl; std::cout << "function returns " << function(a) << std::endl; } int function(A a) { return a.i; } 但是在定义A类之前我无法定义B类,所以我被卡住了.前向声明(未定义)B类也不起作用. 所以我的问题是: 1)为什么我不需要在友谊声明中转发声明函数或整个类,但是如果我需要指定该类的成员函数,我需要定义一个类? 2)如何编译我的代码(除了将B中的A成员对象声明为A * a)? 解决方法
以下是朋友类的示例以及如何使用它.这是
cplusplus.com我发布这个的原因是因为你的例子并没有真正说明在c中正确使用友谊.我希望这能说明你应该如何/为什么要使用友谊,这可以导致你解决你的前瞻性声明问题.
// friend class #include <iostream> using namespace std; class Square; class Rectangle { int width,height; public: int area () {return (width * height);} void convert (Square a); }; class Square { friend class Rectangle; private: int side; public: Square (int a) : side(a) {} }; void Rectangle::convert (Square a) { width = a.side; height = a.side; } int main () { Rectangle rect; Square sqr (4); rect.convert(sqr); cout << rect.area(); return 0; }
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |