[英]wrapper function in throwing error “ as ‘p’ was not declared in this scop”
I am trying to access C++
function (f1) and string a from c
file using a wrapper function. 我试图使用包装函数访问
C++
函数(f1)和c
文件中的字符串a。 Code below. 代码如下。
Error thrown is 抛出的错误是
Error : error: 'p' was not declared in this scope double d = f11( p,i);
错误:错误:'p'未在此范围内声明double d = f11(p,i);
1.h 1.H
double f11(struct c* p, int i);
1.cpp 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 2.C
#include<stdio.h>
#include "1.h"
int main()
{
int i=9;
double d = f11( p,i);
}
If you manually include the contents of "1.h" in main.cpp, it would look: 如果在main.cpp中手动包含“1.h”的内容,它将显示:
#include <stdio.h>
double f11(struct c* p, int i);
int main()
{
int i=9;
double d = f11( p,i);
}
There are several problems there. 那里有几个问题。
You haven't declared p
before using it in the call to f11
. 在调用
f11
之前,您尚未声明p
。
You don't have any way of constructing an object of type struct c
in main
. 你没有任何方法在
main
中构造struct c
类型的对象。 Even if you were to fix the compiler errors by providing declarations of struct c
and p
, you'll run into run time problems since the only way to initialize p
will be to initialize it to NULL. 即使您通过提供
struct c
和p
声明来修复编译器错误,您也会遇到运行时问题,因为初始化p
的唯一方法是将其初始化为NULL。 That wouldn't do you any good since you have a line 因为你有一条线,这对你没有任何好处
return p->f1(i);
in f11
. 在
f11
。
Your declaration and definition of f11
will result in linker error. 您对
f11
声明和定义将导致链接器错误。 If you want to implement the function as extern "C"
, you'll also have to declare it as extern "C"
. 如果要将函数实现为
extern "C"
,则还必须将其声明为extern "C"
。
extern "C" double f11(c* p, int i);
In 1.cpp, the member function f1
does not return a double. 在1.cpp中,成员函数
f1
不返回double。 That is cause for undefined error, if the compiler does not report that as an error. 如果编译器没有将其报告为错误,则导致未定义的错误。
See working code at http://ideone.com/aVFWFJ . 请参阅http://ideone.com/aVFWFJ上的工作代码。 Please note that I changed the implementation of
c::f1
so it does not crash. 请注意,我更改了
c::f1
的实现,因此它不会崩溃。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.