gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 21:39:50 24 4
gpt4 key购买 nike

我正在尝试使用包装函数从 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com