【发布时间】:2015-02-25 04:01:46
【问题描述】:
我正在阅读 C++ Primer 书。它说:
朋友声明仅指定访问权限。这不是一般性声明 功能。如果我们希望类的用户能够调用朋友函数,那么我们 还必须将函数声明与友元声明分开。 为了让类的用户可以看到一个朋友,我们通常声明每个朋友 (在类之外)与类本身在同一个标题中。
注意代码中的箭头。这在参考上述文本的那些特定点上提出了我的问题。
header.h
#ifndef HEADER_H
#define HEADER_H
#include <iostream>
#include <string>
using namespace std;
class Husband{
friend void change_salary(int changed_salary, Husband &ob);
public:
Husband() {}
Husband(unsigned new_salary) : salary{ new_salary } {}
private:
int salary;
};
//void change_salary(int changed_salary, Husband &ob); <----Code Compiles without even this declaration
#endif
main.cpp
#include "header.h"
void change_salary(int changed_salary, Husband &ob)
{
cout << "salary increased by 1000";
ob.salary = changed_salary;
}
int main()
{
Husband hs1{ 3000 };
change_salary(4000, hs1); // <---- Able to use function without explicit declaration outside of class in header
return 0;
}
【问题讨论】:
-
尝试将
change_salary的定义移动到husband.cpp。然后你需要在husband.h中声明函数。 -
@AustinMullins 现在我将 change_salary 代码保存在丈夫.cpp 中并包含“header.h” .....即使这样我的 main.cpp 也可以正确编译,甚至无需单独声明
标签: c++