简体   繁体   English

在CPP类中声明一个C函数作为朋友

[英]declare a C function as friend inside CPP class

I need to use private variable of a class inside a C function. 我需要在C函数中使用类的私有变量。 I was doing something like this 我正在做这样的事情

class Helper
{
private:
    std::string name;
public:
    std::getName(){return name;}
friend extern "C" void initializeHelper();
};

but this code segment gives error unqualified-id before string constant extern "C" { 但此代码段unqualified-id before string constant extern "C" {给出错误unqualified-id before string constant extern "C" {

I am not able to identify what I am doing wrong here. 我无法确定我在这里做错了什么。

Just forward-declare this function before your class: 只需在课前向前声明此函数:

extern "C" void foo();

Then you can use it in friend-declaration: 然后你可以在friend-declaration中使用它:

class A {
public:
  A() {}
private:
  friend void foo();
  int a;
};

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

相关问题 如何在内部 class 内声明与 static function 的朋友? - How to declare friend with static function in Outer class inside the Inner class? 如何在 class 内声明一个模板的朋友 function 并在 ZA2F221ED4F8EBC29DCBDC4 外部实现这个朋友 function - How to declare a friend function of a template inside a class and implement this friend function ouside class? 声明类的C函数好友并返回C枚举器 - Declare C function friend of class and return C enumerator C++ - 如何为类模板声明函数模板好友 - C++ - How to declare a function template friend for a class template 我们如何将带有类模板的友元函数声明到 .h 文件中并将它们定义到 .cpp 文件中(不是全部在一个头文件中)? - How do we declare a friend function with a class template into .h file and define them into a .cpp file (not all in one header file)? 如何向可变参数类声明模板友元函数 - how to declare a template friend function to a variadic class 如何为一个类声明一个朋友函数? - How do I declare a friend function for a class? 声明模板类的模板友元函数 - declare template friend function of template class 如何在c ++中将模板类声明为朋友 - how to declare a template class as a friend in c++ 在C ++中将main()声明为友元函数 - Declare main() as friend function in C++
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM