【问题标题】:Passing instances of objects in C++ class constructors (could not compile) [duplicate]在 C++ 类构造函数中传递对象实例(无法编译)[重复]
【发布时间】:2017-03-02 08:13:34
【问题描述】:

这是我的代码

class B {
public:
    void bar() {std::cout<<"~";}
};

class A {
public:
    A() {b=B();};
    A(B arg_b): b(arg_b) {};
    void foo() {b.bar();};
private:
    B b;
};


int main() {
    A a;
    a.foo();  // works fine

    A aa(B());
    aa.foo();  // could not compile, but if I comment out this line only, it can compile.
}

我收到此错误消息

error: request for member ‘foo’ in ‘aa’, which is of non-class type ‘A(B (*)())’ aa.foo();

我是 C++ 的初学者,谁能解释一下为什么这段代码无法编译?以及通过传入实例来初始化类成员的正确方法是什么?

【问题讨论】:

  • A a(B()); a.foo(); 应该无法编译。请发布真实,完整的代码。 See here for posting guidelines
  • @M.M 感谢您的回复,我已经编辑了代码(如果您建议通过引用传递不能采用右值)
  • 我不是在暗示。阅读发布指南链接。
  • @M.M 嗨,我已经改变了问题(因为还没有人回答),你能解释一下(或给我一个链接)为什么它不能编译吗?谢谢!
  • 当您遇到编译错误时,在问题中包含这些错误被认为是礼貌的。

标签: c++ constructor most-vexing-parse


【解决方案1】:

A aa(B()); 是一个函数声明。所以你不能写aa.foo(),因为你不能在函数上使用.

规则是(大约)如果代码可以被解析为函数声明或对象定义,那么它被解析为函数声明。

相反,您可以使用A aa{ B() };,它不能是函数声明。

Also see this thread

【讨论】:

    猜你喜欢
    • 2014-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-05
    • 1970-01-01
    • 2020-07-27
    相关资源
    最近更新 更多