在这个程序中,我完全理解为什么主函数的第一部分失败并需要注释 - 在我在TestingClass中实现值ctor后没有隐式的默认ctor。完全合乎逻辑。但是,我发现第二部分(test2对象的创建)成功,至少在gcc 4.8.4中,我有点惊讶。没有默认构造函数的初始化时的赋值
#include <iostream>
using namespace std;
class TestingClass
{
public:
TestingClass(int inVal)
{
val = inVal;
}
int val;
};
TestingClass testingCreator()
{
return TestingClass(100);
}
int main()
{
/*
TestingClass test1;
test1 = testingCreator();
cout << "Test1: " << test1.val << endl;
*/
TestingClass test2 = testingCreator();
cout << "Test2: " << test2.val << endl;
}
关于它的思考,这也是情理之中,因为对象,TEST2,以后再也没有被修建/初始化存在,但大多数人在这种思维方式初始化为只是做了声明和赋值在一条线上。显然,虽然初始化比这个更特别,因为这个代码有效。
这是标准C++吗?它是否可以跨编译器工作?我感兴趣的是如何以这种方式初始化不同于声明(使用默认ctor)然后赋值(通过在全局函数中创建的临时对象)。
UPDATE:增加了一个副本ctor和明确使用copy ctor的第三种情况。
#include <iostream>
using namespace std;
class TestingClass
{
public:
TestingClass(const TestingClass &rhs)
{
cout << "In copy ctor" << endl;
this->val = rhs.val + 100;
}
TestingClass(int inVal)
{
val = inVal;
}
int val;
};
TestingClass testingCreator()
{
return TestingClass(100);
}
int main()
{
/*
TestingClass test1;
test1 = testingCreator();
cout << "Test1: " << test1.val << endl;
*/
TestingClass test2 = testingCreator();
cout << "Test2: " << test2.val << endl;
TestingClass test3(test2);
cout << "Test3: " << test3.val << endl;
}
此输出:
Test2: 100
In copy ctor
Test3: 200
“但是大多数人会这样认为初始化只是作为一行中的声明和赋值”......而不是大多数C++程序员。 (希望没有任何!) –