简体   繁体   English

C ++没用的朋友函数声明

[英]C++ Useless Friend Function Declaration

Well, I declared a friend function which is in: 好吧,我在下面声明了一个朋友函数:

// user-proc.h
class cregister{
 private:
  levy user; // typedef struct
  int testp;
 public:
  friend void test();
  cregister(levy &tmp);
  levy getUser();
  void displayUser(levy &);
};

Then I defined it in: 然后我在下面定义它:

// user-proc.cpp
void test()
{
    cout << "test" << endl;
}

And I'm trying to call in main function but it gives me It wasn't declared in this scope. 我试图调用main函数,但是它给了我在此范围内未声明。 I did some research but what I find is, they saying friend type is not exactly declaration you have to define it out of class also. 我做了一些研究,但发现的是,他们说朋友类型并不一定就是声明,您也必须在课外定义它。 I tried it then normally error gone but as it happens friend functions cannot access private members. 我尝试了一下,然后错误通常消失了,但是当它发生时,朋友功能无法访问私有成员。

EDIT : I used void test(); 编辑:我用无效test(); before class-definition and used object to access private members. 在类定义之前,并使用对象访问私有成员。 It fixed that way. 它固定了这种方式。

You need to have two declarations: One normal function prototype declaration, and another in the class as a friend declaration. 您需要有两个声明:一个正常的函数原型声明,另一个在类中作为Friend声明。


// user-proc.h
void test();  // Added prototype

class cregister{
 private:
  levy user; // typedef struct
  int testp;
 public:
  friend void test();  // Friend declaration still here
  cregister(levy &tmp);
  levy getUser();
  void displayUser(levy &);
};

It looks like there are two test() functions declared here; 看起来这里声明了两个test()函数; one in the class and one (with definition) in the cpp file. 在类中一个,在cpp文件中一个(带定义)。

The test() that is only declared in the class is effectively only accessible via ADL and this won't work here since it takes no arguments of the type of the class. 仅在类中声明的test()只能通过ADL进行有效访问 ,因此在这里不起作用,因为它不接受类类型的参数。

Add a declaration of void test(); 添加一个void test();声明void test(); before the class definition should make the internals of the class available in the test function. 在类定义之前,应该使的内部信息在test函数中可用。

// user-proc.h

void test();

class cregister{
 // redacted...
 public:
  friend void test();
};

Whilst test() has access to the private members here, unless it declares an instance of the class (a valid object) to work with, the function is not too useful. 尽管test()可以在此处访问私有成员,除非它声明要使用的类的实例(有效对象),否则该功能不是很有用。 Consider adding an argument for the function , something such as void test(cregister& arg); 考虑为函数添加参数 ,例如void test(cregister& arg); (and here ADL would kick in). (然后ADL就会加入)。 I infer that the function here is specifically for testing, so the above may not apply, but in the general case it could be useful. 我推断这里的功能专门用于测试,因此以上内容可能不适用,但在一般情况下它可能很有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM