强制编译器在C++; 我编写了一个C++程序,但没有定义任何构造函数。代码如下: #include<iostream> using namespace std; class test { public: void print() { cout<< "Inside Print"<<endl; } }; int main() { test t; t.print(); return 0; } #include<iostream> using namespace std; class test { public: test() { } void print() { cout<< "Inside Print"<<endl; } }; int main() { test t; t.print(); return 0; }

强制编译器在C++; 我编写了一个C++程序,但没有定义任何构造函数。代码如下: #include<iostream> using namespace std; class test { public: void print() { cout<< "Inside Print"<<endl; } }; int main() { test t; t.print(); return 0; } #include<iostream> using namespace std; class test { public: test() { } void print() { cout<< "Inside Print"<<endl; } }; int main() { test t; t.print(); return 0; },c++,constructor,C++,Constructor,如您所见,在上述代码段(第21行)中只有一条call指令。它正在调用print()函数。现在我稍微修改了代码,并引入了构造函数。代码如下: #include<iostream> using namespace std; class test { public: void print() { cout<< "Inside Print"<<endl; } }; int main()

如您所见,在上述代码段(第21行)中只有一条
call
指令。它正在调用
print()
函数。现在我稍微修改了代码,并引入了
构造函数
。代码如下:

#include<iostream>
using namespace std;
class test
{
    public:

        void print()
        {
            cout<< "Inside Print"<<endl;
        }
};
int main()
{
   test t;
   t.print();
   return 0;
}
#include<iostream>
using namespace std;
class test
{
    public:
        test()
        {
        }
        void print()
        {
            cout<< "Inside Print"<<endl;
        }
};
int main()
{
    test t;
    t.print();
    return 0;
}
如您所见,它在第21行中调用了构造函数。 现在我的问题是,如果我没有在代码中定义任何构造函数,编译器不是在所有情况下都提供默认构造函数吗?如果没有,那么在什么情况下,或者更确切地说,如何强制编译器为我提供默认构造函数


很抱歉问了这么长的问题:p

程序按其应有的方式运行。机器代码生成不是标准的一部分,您无权期望任何特定的机器代码输出-您只能保证输出程序按照您告诉它的方式执行。

为什么要强制编译器增加二进制代码并降低程序速度

好的编译器只会在有意义的情况下调用默认构造函数(或任何其他函数),如果调用它会产生任何效果

优化只会从程序中排除默认构造函数(它什么也不做)调用

如果我没有在代码中定义任何构造函数,编译器不是在所有情况下都提供默认构造函数吗

不,仅当您不定义任何其他构造函数时。如果您的类有任何用户声明的构造函数,那么这将抑制默认构造函数的隐式声明

即使不定义其他构造函数,除非默认构造函数实际上必须执行某些操作,例如调用基类或成员变量的非平凡构造函数,否则它将是平凡的,因此不会执行任何操作,因此不需要生成代码。只有愚蠢的编译器才会生成一个完全空的函数,并坚持调用它只是为了什么都不做

如果没有,那么在什么情况下,或者更确切地说,如何强制编译器为我提供默认构造函数

如果你想确保它存在,那么就定义它,但是如果它什么都不做,那就是浪费时间。如果它需要执行诸如构造基类或成员变量之类的操作(并且它不会被另一个用户声明的构造函数禁止),那么它将由编译器创建


编译器正在做正确的事情,您不需要强制它做任何事情。

构造函数没有创建,因为它不需要。没有要构造的东西。但是当我创建一个对象时,应该调用构造函数,对吗???尝试关闭所有优化。例如,
static\u cast(0)
是一个可能不会创建任何机器代码的有效表达式;然而,这是一个非常明智的C++语句。