c++ - 为什么用()声明对象时不调用构造函数?

标签 c++ constructor most-vexing-parse

<分区>

Possible Duplicate:
Why is it an error to use an empty set of brackets to call a constructor with no arguments?

$ cat cons.cpp
#include <iostream>

class Matrix {
private:
    int m_count;

public:
    Matrix() {
        m_count = 1;
        std::cout << "yahoo!" << std::endl;
    }
};

int main() {
    std::cout << "before" << std::endl;
    Matrix m1();                         // <----
    std::cout << "after" << std::endl;
}
$ g++ cons.cpp
$ ./a.out
before
after
$

语法 Matrix m1(); 有什么作用?

我认为它与 Matrix m1; 相同。显然我错了。

最佳答案

Matrix m1(); // m1 is a function whose return type is Matrix.

此 C++ FAQ lite 条目也应该有所帮助。

Is there any difference between List x; and List x();

关于c++ - 为什么用()声明对象时不调用构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9451437/

相关文章:

c++ - 为什么 std::function 在这种情况下不起作用?

c++ - 在可变模板函数中为每个模板类型调用 void 函数?

c++ - 伪终端和串行设备之间奇怪的字符替换

JavaScript继承: subtype prototype cannot visit super type's property/function

javascript - 我的构造函数有什么问题

php - 如何在 laravel Controller 构造函数中获取登录用户

c++ - 这个声明如何调用最令人烦恼的解析?

c++ - 在 C++ 中使用 RAII 在线程包装类中 move 语义

c++ - 二进制通用 lambda 不匹配 ptr 到函数参数?

c++ - long long在C++中是如何实现的?