C++学习之路: class类外的成员函数定义 和 友元 的讨论

引言:成员函数定义在类内和类外的区别在于是否内联展开。

定义在类内一般都是内联展开的, 节省了调用函数的开销。如果函数体过于庞大,编译器会忽视内联建议

 

如果定义在类外,需要在类内声明,则程序运行时 是采用调用的方式 访问该函数,是非内联的方式。

 

 1 #include <iostream>
 2 #include <string>
 3 #include <vector>
 4 using namespace std;
 5 
 6 class Student
 7 {
 8     public:
 9         Student();
10         Student(int id, const string name, int age);
11         void print() const;
12     private:
13         int id_;
14         string name_;
15         int age_;
16 };
17 
18 Student::Student()
19     :id_(0),
20      name_(""),
21      age_(0)
22 {
23 }
24 
25 Student::Student(int id,
26                  const string &name,
27                  int age)
28     :id_(id),
29      name_(name),
30      age_(age)
31 {
32     
33 }
34 
35 void Student::print() const
36 {
37     cout << "hello" << endl;
38 }

 

 

 

下面我们 讨论一下友元 和 类对象的 关系。

 

 1 #include <iostream>
 2 #include <string>
 3 #include <vector>
 4 using namespace std;
 5 
 6 class Test
 7 {
 8     public:
 9         friend class Other; //声明Other是Test的朋友
10         friend void bar(const Test &t);
11     private:
12         int x_;
13         int y_;
14 };
15 
16 class Other
17 {
18     public:
19         void foo(Test &t)
20         {
21             t.x_ = 10;
22             t.y_ = 20;
23         }
24 };
25 
26 void bar(const Test &t)
27 {
28     cout << t.x_ << endl;
29 }
30 
31 int main(int argc, const char *argv[])
32 {
33     Test t;
34     return 0;
35 }

 

通过上面的代码我们可以看到, 友元是可以直接访问,对象的私有数据的,   你只需要在class中声明一下 XX 类 是我的朋友即可, 关键字为friend。

函数也可以用 friend 关键字 来声明,则该函数可以直接访问 class 内的private 数据。

转载于:https://www.cnblogs.com/DLzhang/p/3986069.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值