构造函数参数无法识别

时间:2015-05-24 00:14:48

标签: c++ constructor

在尝试在以下代码中构建嵌套类#include <cstdio> using namespace std; struct A{ int n; A(): n(1){} struct B{ A& a; B(A a): a(a){ a.n=2; } ~B(){ a.n=0; } }; }; int main() { A a; printf("%d\n",a.n); do{ A::B(a); printf("%d\n",a.n); }while(false); printf("%d\n",a.n); return 0; } 的实例时,我收到编译器错误:

A::B

当我调用/** * Provide a block grid of customized size and * a block moving back and forth at the center * of the block grid. * @author .. * @version .. */ public class BlockGrid { ..... } /** * This is to use the input width, height, and pixel to * get the actual pixel and place it. */ class MyWindow extends JFrame implements Runnable { .....(some ints here) /** Constructor * use to show the graph of the grid with new height, * and width depending on new pixel. * @param w This is the logical number of blocks in the width direction. * @param h This is the logical number of blocks in the height direction. * @param p This is the size of each grid square. */ public MyWindow(int w, int h, int p) { ..... } } 的构造函数时,编译器无法识别该参数。我做错了什么?

2 个答案:

答案 0 :(得分:2)

此行不符合您的预期:

A::B(a);

括号实际上是多余的。该行相当于:

A::B a;

B没有默认构造函数,因此编译错误。您需要为该对象提供一个名称,您可以将其命名为_,作为其作为范围保护的唯一指示:

A::B _(a);

答案 1 :(得分:1)

这基本上是最令人烦恼的解析的变体。代码:

CriticalSection::Locker(cs);

...没有定义CriticalSection::Locker类型的对象,因为您还没有根据需要向ctor提供参数。

治愈方法是定义对象的名称:

CriticalSection::Locker lock(cs);

你也可以使用&#34; universal&#34;初始化:

CriticalSection::Locker lock{cs};

这样,如果您不小心忽略了您要定义的对象的名称,您可能会收到一条错误消息,该消息至少可以更明确地说明什么是&#39;继续。

顺便说一下:除非你确定从使用wx变种中获得了一些东西,否则我至少会考虑使用std::mutexstd::lock_guard