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