c++ - 将指针传递给构造函数时没有调用错误的匹配函数

标签 c++ pointers

<分区>

这可能是 C++ 初学者的错误,但我现在对这个编译器错误感到很困惑:

error: no matching function for call to 'B::B(A (*)())'
note: candidates are: B::B(A*)

我写了两个看起来像这样简化的类:

//a very simple class A
class A
{
public:
    A()
    {
        //do some stuff in Constructor
    }
}

//another class, that stores a pointer to an object of A as a field
class B
{
private:
    A* _a;

public:
    //simply initialize the field in Constructor
    B(A* a) : _a(a) { }

    void doMagic()
    {
        //do something with _a
        _a->xyz();
    }
}

我在我的代码中调用的是这样的:

A a();
B b(&a); //here the error appears

我想要的是创建一个对象a并将它的指针传递给对象b。这样我就可以访问 a in b 的成员。

肯定只是B的调用中的东西 b(&a);也许您可以很容易地找出我的问题所在。

最佳答案

您不是在创建 A 类型的对象,相反,A a(); 是一个函数声明,它不带参数,返回类型是 A。所以你试图将函数指针传递给 B 的构造函数,这就是编译器所提示的。你应该改变

A a();

A a;

关于c++ - 将指针传递给构造函数时没有调用错误的匹配函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32225663/

相关文章:

c++ - 指针初始化之间的区别

C - memcpy 和复制结构

c# - 如何确定一个位序列是正数还是负数

c++ - 在 vector 中存储各种类型

c++ - 是否有与 timeGetTime() 等效的标准库?

c++ - 使用 `std::copy()` 和 `std::back_inserter()`

C指针转换规则

c++ - 从目标文件列表 (*.o) 构建库 (lib.a) 的 makefile

C 转换为 void 指针时可能溢出

c++ - 无法弄清楚 int[3][3] 和 int(* const)[3] 之间的区别