首页 \ 问答 \ 如何正确访问好友功能?(How to access friend functions correctly?)

如何正确访问好友功能?(How to access friend functions correctly?)

我正在尝试访问朋友的方法,如下所示。 我有4个文件。 两个标题:

标题ah

#include "b.h"

class A
{
public:
    A();
    ~A();
    void testStuff(int i);
};

标题bh

#include "a.h"

class A;

class B
{
    friend class A;

public:
    B();
    ~B();
    friend void doStuff(int i);
};

两个包括一些代码, a.cpp

#include "a.h"

void A::testStuff()
{
    B b {B()};
    b->doStuff(1);
}

b.cpp

#include "b.h"

void B::doStuff(int i)
{
    m_stuff = i;
}

如果我删除关键字friend一切正常。 但是如果我将doStuff()声明为朋友,我会收到以下错误:

error: ‘class B’ has no member named ‘doStuff’

我尝试过这个教程。 我错过了什么?


I'm trying access a friend's method as defined the following. I have 4 files. Two header:

Header a.h:

#include "b.h"

class A
{
public:
    A();
    ~A();
    void testStuff(int i);
};

Header b.h:

#include "a.h"

class A;

class B
{
    friend class A;

public:
    B();
    ~B();
    friend void doStuff(int i);
};

And two including some code, a.cpp:

#include "a.h"

void A::testStuff()
{
    B b {B()};
    b->doStuff(1);
}

b.cpp:

#include "b.h"

void B::doStuff(int i)
{
    m_stuff = i;
}

If I remove the keyword friend everything works fine. But if I declare doStuff() as a friend, I get the following error:

error: ‘class B’ has no member named ‘doStuff’

I tried following this tutorial. What do I miss?


原文:https://stackoverflow.com/questions/24087193
更新时间:2019-12-03 08:12

最满意答案

您对friend功能的理解是错误的 。 如果将函数friend声明为另一个类,则表示friend函数可以访问该类的私有成员,这并不意味着friend函数成为类成员

这里doStaff()B friend ,而不是B的成员。 但是你在B的对象上使用它,因此编译器说它不是该类的成员。 使用frienddoStaff权限访问Bprivate成员。

您所关注的教程清楚地说明了这一点。 duplicate()方法是Rectangle的朋友,因此它可以访问private成员的widthheight ,但duplicate()不用作Rectangle的类方法。

总之,你的问题是错误的。 您可以像任何免费 (非类方法)功能一样访问friend功能。 问题是friend函数如何访问它所属的类的成员,并且如上所述,它可以访问该类中的所有内容,这是拥有朋友函数的动机,即允许访问类的私有成员一个局外人。

类似地, friend类可以访问它所熟悉的类的所有内容。

因此,对于您的问题,要么从doStaff移除friend以使其成为B的成员。 但我想你的意图是使用friend方法,在这种情况下你可以做到以下几点:

void doStuff(B b, int i)
{
  b.m_stuff = i; // it is friend function of B, so can access m_staff
}

或者你可以成为A doStaff()成员然后你可以写

class A{
  //other members
  void doStaff(B& b, int i){ b.m_staff=i;}

void A::testStuff() {

  B b {B()};
  doStuff(b,1); //although u can just write "b.m_staff = 1;" right here
}

Your understanding regarding friend function is wrong. If you declare a function friend to another class, it means the friend function can access private members of that class, it does not mean the friend function becomes a class member.

Here doStaff() is friend to B, not a member of B. But you are using it on an object of B, hence compiler saying that it is not member of that class. using friend gives doStaff permission to access B's private members in it.

The tutorial you are following says it clearly. duplicate() method is a friend to Rectangle, hence it can access the private members width and height, but duplicate() is not used as a class method of Rectangle.

In summary, your question is wrong. You can access a friend function just like any free (non-class method) function. The question is how friend functions accesses the member of a class to which it is friend, and as said, it can access everything in that class, which is the motivation of having friend functions, namely to give access of private members of a class to a outsider.

Similarly a friend class can access everything of the class to which it is friend.

So for your problem, either you remove friend from doStaff to make it a member of B. But I guess your intention was to use friend method, in that case you can do the following:

void doStuff(B b, int i)
{
  b.m_stuff = i; // it is friend function of B, so can access m_staff
}

or you can make doStaff() member of A and then you can write

class A{
  //other members
  void doStaff(B& b, int i){ b.m_staff=i;}

void A::testStuff() {

  B b {B()};
  doStuff(b,1); //although u can just write "b.m_staff = 1;" right here
}
2014-06-07

相关问答

更多

如何使该功能可以在OpenCV中处理不同类型的图像(How to make the function can process different type image in OpenCV)

你不能用cv::Mat做到这一点。 但是,您可以使用cv::Mat_并进行一些模板化: template<typename T> cv::Mat_<T> drop_rows_int(cv::Mat_ mat, vector<int> v) { ... } 在这里你提取类型为T的指针。 只是一条建议,出于效率目的,如果可能的话,我建议将矢量v作为const参考发送。 这是完整的解决方案: #include "opencv/cv.h" #include <vector> #include <ios

在离子3应用程序中使用JWT进行身份验证(Using JWT for authentication in an ionic 3 application)

你可以使用angular2-jwt ,它可以很好地工作并自动发送你的令牌与你的所有http请求,你可以很容易地管理你的令牌到期 你只能从配置文件中给出来自离子存储的访问令牌的来源,这里是离子的配置: import { JwtModule, JWT_OPTIONS } from '@auth0/angular-jwt'; import { Storage } from '@ionic/storage'; export function jwtOptionsFactory(storage) { r

如何用特定的类获得特定'li'的值(How to get value of specific 'li' with specific class)

您在每次选择时多次将点击事件绑定到按钮。 删除按钮单击绑定并将其放在菜单功能之外。 看小提琴 $(function () { var selection ; $(".menu").menu({ select: function (event, ui) { $('.selected', this).removeClass('selected'); // add the css class as well as get the text va

班级没有运行(Class Not Running)

这些类没有运行的原因是因为没有任何东西在调用它们。 与视图控制器关联的类未调用该类: BLEController.h #import <Foundation/Foundation.h> @interface BLEController : NSObject { enter code here NSMutableArray *_periphralItems; } @end BLEController.m #import "SensorDev.h" #import "Discovery.h"

如何仅显示文本文件数组中的Read-Host值?(How to show only Read-Host value from a text file array?)

您只需要一个if语句来检查以确保您的输入与其在每行上读取的作业标题相同。 $jobtitledb = Get-Content C:\Users\Username\Desktop\Scripts\JobTitle.txt $jobtitleinput = Read-Host 'Input the job title' foreach($data in $jobtitledb) { $jobtitle, $basic, $extended = $data -split ',' If ($job

如何退出PSQL CREATE FUNCTION屏幕(How to exit PSQL CREATE FUNCTION screens)

尝试CTRL + C. 它丢弃了没有终止引号的最后一个查询。 First, I figured out that postgres functions can't start with a number. ERROR: syntax error at or near ".99" LINE 1: CREATE OR REPLACE FUNCTION public.99cents(money) Secondly, to exit out of the issue above the $funct

Spring3 + JSF复合组件(Spring3 + JSF Composite components)

在test.xhtml ,复合组件的命名空间是错误的。 改变它: xmlns:util="http://java.sun.com/jsf/composite/ui/util" 至: xmlns:util="http://java.sun.com/jsf/composite/ui" The problem is that JSF Composite doenst like my CustomResource, made a workaround that and its working now

如何使用后退按钮返回上一页/使用react-router-dom链接点击(How to go back to previous page using back button/Link click using react-router-dom)

我相信你的情况与auth示例非常相似,你需要记住用户来自的网页https://reacttraining.com/react-router/web/example/auth-workflow 在页面A和页面B中,您可以在其中添加链接 <Link to={{ pathname: '/form1', state: { from: props.location } // or '/A' or '/B' }} /> 在Form1中,您需要访问location因此您可能需要使

相关文章

更多

最新问答

更多
  • 根据Woocommerce中的自定义字段计算自定义购物车商品价格(Custom cart item price calculation based on dimentions custom fields in Woocommerce)
  • 分开foreach项目并单独打印(Separate foreach items and print them individually)
  • 写模式管道是否同步?(Is write mode pipe synchronous?)
  • 发现可用的Windows Phone强调色和本地化名称(Discover available Windows Phone accent colors and localized names)
  • 使用多线程和WPF更新集合(Update Collection with multithreading and WPF)
  • 如何在字符串的情况下使用同步?(How should the synchronization be used in case of strings?)
  • 打印唯一的行,比较不超过N个字符(Print unique lines, compare no more than N characters)
  • Javascript / jQuery - 如何调用switch case从另一个函数执行(Javascript/jQuery - how to call a switch case to execute from another function)
  • Hbase超时错误不断发生(Hbase timeout errors keep occuring)
  • 如何在Delphi中更改TabControl中活动TAB的颜色(How to change the color of active TAB in a TabControl, in Delphi)
  • 正则表达式:在sublime文本中替换一些PHP代码(Regex: replace some pieces of php code in sublime text)
  • 在带有Scene2D的LibGDX中,如何在按下按钮时连续向右走?(In LibGDX with Scene2D, how can I continuously walk to the right when a button is pressed?)
  • 累加器如何在Haskell中工作?(How do accumulators work in Haskell?)
  • 使用开关检查市场和前缀与正确的货币符号(using switch to check market and prefix with correct currency symbol)
  • 在哪里分配一次使用类?(Where to allocate one time use class?)
  • 如何从两个DateTime / NaiveDateTime获取持续时间?(How do I get Duration from two DateTime / NaiveDateTime?)
  • 解析TimeSpan大于24小时?(Parse a TimeSpan greater than 24 hours? [duplicate])
  • 如何在球拍中本地更改阅读规则?(How to locally change reading rules in racket?)
  • 数据库应该由DI注入时的模拟存储(通过构造函数)(Mock storage when database should be injected by DI (through constructor))
  • 使用maven集成2个eclipse项目(Integrate 2 eclipse projects using maven)
  • 角度ng-repeat不检测变化(Angular ng-repeat not detecting changes)
  • Xaml组件在Silverlight + XNA应用程序的多个页面中可见(Xaml component visible in multiple pages in Silverlight+XNA applications)
  • 如何将`var`变量等同于另一个查询(How to equate `var` variable to another query)
  • 如何设计hyperledger链代码以适合您的业务?(how to design your chaincode of hyperledger to fit for your business?)
  • PHP readfile错误(PHP readfile error)
  • 在Date之后排序列表然后是时间(Sorting list after Date then time)
  • Android内部版本号(Android build number)
  • 在没有预设退出条件的情况下停止无限循环(stopping an infinite loop with no preset exit condition)
  • Phonegap应用程序全屏通过html页面中的按钮(Phonegap Application fullscreen through a button in html page)
  • PAA是否适合在门户网站中自动执行wcm库部署和设置?(Is PAA a good candidate for automating wcm library deployment and setup in portal?)