相关疑难解决方法(0)

内联朋友功能的范围是什么?

在搜索到SO之后,一个问题告诉我,内联友元函数的词法范围是它定义的类,这意味着它可以访问例如typedef类中的s而不限定它们.但后来我想知道这种功能的实际范围是什么?海湾合作委员会至少拒绝我所有打电话的尝试.可以通过除ADL以外的方式调用示例中的函数,由于没有参数,这是不可能的吗?

标准报价表示赞赏,因为我目前无法访问我的副本.

以下代码

namespace foo{
  struct bar{
    friend void baz(){}
    void call_friend();
  };
}

int main(){
  foo::baz();           // can't access through enclosing scope of the class
  foo::bar::baz();    // can't access through class scope
}

namespace foo{
  void bar::call_friend(){
    baz();    // can't access through member function
  }
}
Run Code Online (Sandbox Code Playgroud)

导致这些错误:

prog.cpp: In function ‘int main()’:
prog.cpp:9: error: ‘baz’ is not a member of ‘foo’
prog.cpp:10: error: ‘baz’ is not a member of ‘foo::bar’
prog.cpp: In member …
Run Code Online (Sandbox Code Playgroud)

c++ scope inline friend

32
推荐指数
2
解决办法
5911
查看次数

在结构中使用友元函数有什么用?

我使用以下语法在结构中重载插入运算符(<<):

struct Address{
    string street;
    string cross;
    int suite;

    friend ostream &operator <<(ostream &oss, const Address &other){
        oss<<"street: "<<other.street<<"cross: "<<other.cross<<"suite: "<<other.suite;
        return oss;
    }
};
Run Code Online (Sandbox Code Playgroud)

我看到,只有当我将该函数声明为struct'Address'的朋友时才会编译我的代码.根据我的理解,当需要访问类的私有成员时,友元函数很有用.但是,因为在结构中所有成员都是公共的,所以不应该将'<<'运算符声明为朋友.

有人可以澄清是否需要在这里声明'<<'运算符作为结构'地址'的朋友?

c++ struct friend c++11

1
推荐指数
1
解决办法
258
查看次数

标签 统计

c++ ×2

friend ×2

c++11 ×1

inline ×1

scope ×1

struct ×1