问题描述
问题标出了, A(); //不应该A::A()吗?
#include <iostream>#include <string>using namespace std;class A{public: A() {cout << 'A constructor' << endl; } ~A() {cout << 'A destructor' << endl; }};int main(){ A(); //不应该A::A()吗? cout<<'end xxxn'; cout<<'end yyyn';}
问题解答
回答1:正常的调用应该是
int main(){ A a = A(); //不应该A::A()吗? cout<<'end xxxn'; cout<<'end yyyn';}
类比一下一个由返回值的函数
int add(int a, int b);
可以这样调用
int c = add(1, 2);
当然也可以这样调用了
add(1, 2);回答2:
因为这是构造函数啊。。。所以这相当于创建了一个临时对象,构造函数为啥要写两次类名呢

  