c++ - 抛出错误 "as ‘p’ 中的包装函数未在此范围内声明”

标签 c++ c string wrapper member-functions

我正在尝试使用包装函数从 c 文件访问 C++ 函数 (f1) 和字符串 a。代码如下。

抛出的错误是

Error : error: ‘p’ was not declared in this scope double d = f11( p,i);

1.h

double f11(struct c* p, int i);

1.cpp

#include<iostream>
using namespace std; 
class c
{
    public:   double f1(int i)  // how can i access from c 
    {
        cout<<"I am in c++";
    }
    public : string a;   // how can i access string from c
};

extern "C"  double f11(c* p, int i) // wrapper function
{
    return p->f1(i);
}

2.c

#include<stdio.h>
#include "1.h"
int main()
{
    int i=9;
    double d = f11( p,i);
}

最佳答案

如果您在 main.cpp 中手动包含“1.h”的内容,它将如下所示:

#include <stdio.h>

double f11(struct c* p, int i);

int main()
{
    int i=9;
    double d = f11( p,i);
}

那里有几个问题。

  1. 在调用 f11 之前,您尚未声明 p

  2. 您无法在 main 中构造类型为 struct c 的对象。即使您通过提供 struct cp 的声明来修复编译器错误,您也会遇到运行时问题,因为初始化 p 的唯一方法 将其初始化为NULL。那对你没有任何好处,因为你有一条线

    return p->f1(i); 
    

    f11 中。

  3. f11 的声明和定义将导致链接器错误。如果您想将函数实现为 extern "C",您还必须将其声明为 extern "C"

    extern "C" double f11(c* p, int i);
    
  4. 在1.cpp中,成员函数f1不返回double。如果编译器没有将其报告为错误,这就是未定义错误的原因。

请参阅 http://ideone.com/aVFWFJ 处的工作代码.请注意,我更改了 c::f1 的实现,因此它不会崩溃。

关于c++ - 抛出错误 "as ‘p’ 中的包装函数未在此范围内声明”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32063360/

相关文章:

c - 就地与返回 C 中的新设计模式

python - 在c中读取python的全局变量

在 C 中连接字符串

javascript - 如何将字符串保存到 p5.js 中的特定位置

java - 在Java中正确使用Regex,Regex不匹配

c++ - 使用 Trie 自动完成

c++ - C++ 格式化输出

c++ - 将一个 vector 映射到不同的对,即使 vector 在映射到每一对时是不同的?

c++ - 使用cmake和vs2010链接到静态boost lib而不自动链接

C - 'typedef struct SymTable *SymTable_T; 是什么意思?意思是?