【问题标题】:a value of type "Struct*" cannot be assigned to an entity of type "Struct*"“Struct*”类型的值不能分配给“Struct*”类型的实体
【发布时间】:2014-04-05 14:33:59
【问题描述】:

我有一个返回结构类型指针的函数。我想要的是 pFacialFeatures 指向与返回指针相同的地址。

struct Features
{
    CvRect* face_;
    CvRect* nose_;
    CvRect* eyesPair_;
    CvRect* rightEye_;
    CvRect* leftEye_;
    CvRect* mouth_;
};

Features* Detect()
{
    Features* facialFeatures = (Features*) malloc(sizeof(Features));
    return facialFeatures;
}

int main(int argc, char* argv[])
{
    Features* pFacialFeatures;
    pFacialFeatures = Detect();
}

它给了我错误:

IntelliSense:“Features *”类型的值不能分配给“Features *”类型的实体

注意:也许你会认为这个问题和这个one是一样的。在那个问题中,声明结构存在问题。我真的声明了struct。

【问题讨论】:

  • 这是 C++ 代码。 @BLUEPIXY
  • 这可能是智能感知问题吗?如果你继续编译会发生什么?
  • C++ 没有问题。您是否尝试将其编译为 C?
  • IntelliSense 有时会向您显示不存在的错误。代码在 VS11 下编译(至少如果我在代码中添加一个占位符 struct CvRect {int i;}; 并包含 stdlib.h)。
  • @KMetin 我问是因为如果您将该代码放入文件中并编译,则会出现更多错误。

标签: c++ pointers struct


【解决方案1】:

您以某种方式告知 Visual Studio 这是一个 C 源文件而不是 C++ 源文件 - 可能是通过将文件命名为“something.c”或将其放在头文件中,然后从“.h”中包含它” 文件或通过悬挂“extern C”或以某种方式将文件或项目的属性设置为“编译为 C”。如果您使用的是 Linux/MacOS,您可能已经通过使用 C 编译器而不是 C++ 编译器来完成它,例如通过输入“gcc foo.cpp”而不是“g++ foo.cpp”

结构声明的 C 语言语法与 C++ 中的不同。

C++ 语句

struct Foo {}; // C++

等价于C语言:

typename struct tagFoo {} Foo; // C

所以下面的代码可以在 C++ 中运行,但在 C 中失败:

struct Foo {};
Foo* f = (Foo*)malloc(sizeof(Foo));

更改它以检查 C++ 的快速方法是替换:

Features* facialFeatures = (Features*) malloc(sizeof(Features));

Features* facialFeatures = new Features;

如果您在 C 模式下编译,您将收到关于 new 的编译器错误。它是 C++ 中的关键字,但不是 C 中的关键字。

用C写你的行的方法是

struct Features* facialFeatures = malloc(sizeof* facialFeatures);

【讨论】:

  • C 的写法是struct Features *facialFeatures = malloc(sizeof *facialFeatures);Don't cast malloc
【解决方案2】:

我相信你需要把 struct 放在类型声明之前:

struct Features* facialFeatures = (struct Features *)malloc(sizeof(struct Features));

【讨论】:

    猜你喜欢
    • 2021-01-17
    • 2021-02-10
    • 1970-01-01
    • 2015-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-25
    • 1970-01-01
    相关资源
    最近更新 更多