C++用括号声明一个对象

标签 c++ constructor

<分区>

Possible Duplicate:
Error on calling default constructor with empty set of brackets

我附上了一个测试程序。 问题:

如果我像下面这样声明,就没有对象被创建并且 不调用默认构造函数。 'grCell c3();'//不好

但是, 像这样声明是可以的。创建一个对象并调用其构造函数。 'grCell c1;'//很好

'grCell c3()' 和 'grCell c1' 有什么区别?

谢谢!

托德

//----开始--------

#include <iostream>
#include <cstdio>

typedef unsigned int uint;
using namespace std; 

//
class grCell {
 public:
  grCell()      { printf("HERE_0\n"); };
  grCell(int i) { printf("HERE_1\n"); };
  ~grCell() {};

  void setX(int x) { _x = x; }
  //
  //
private:


  int  _x:22;
};

int main()
{

  grCell c1;  // good
  c1.setX(100);


  grCell c3();  // bad
  c3.setX(100);

  grCell c2(5);
  c2.setX(10);


} 

//------ 结束 ------

最佳答案

What is the difference between grCell c3() and grCell c1 ?

第一个声明一个函数,而第二个创建一个名为 c1 的对象,类型为 grCell

grCell c3();

它不创建对象,而是声明一个名称为 c3 的函数,该函数不接受任何参数并返回类型为 grCell 的对象。
它是 Most vexing parse 在 C++ 中。

关于C++用括号声明一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12470459/

相关文章:

c# - 类型初始化异常

Java 类和构造函数

c++ - 模板化类的模板化成员的函数句柄

c++ - 将字符串从 UTF-8 转换为 ISO-8859-1

c++ - 如何在 C++ 中获取当前 CPU 和 RAM 使用情况?

c++ - 使用 << 或 >> 连接一个无符号字符数组

c# - 在调用方法之前将对象存储在变量中有好处吗?

c++ - C++ 中的 PeekMessage 函数和命名管道

c++ - 关于c++构造函数的问题

java - Java 强制您提供无参数构造函数背后的逻辑是什么?