我遇到了一个课程编程问题,它要求我初始化A a
using 引用传递(初始化A a
中的func
)。如何通过' 引用调用A
' 构造函数?A
#include <iostream>
using namespace std;
class A
{
public:
int x;
A()
{
cout << "default constructor" << endl;
x = 1;
}
A(int x)
{
cout << "constructor with param = " << x << endl;
this->x = x;
}
~A() {
cout << "destructor" << endl;
}
void print() {
cout << x << endl;
}
};
void fun(A& a)
{
a.A::A(10); // error!
return;
}
int main()
{
A a;
fun(a);
a.print();
return EXIT_SUCCESS;
}
这个问题是有背景的。老师要我们复制NRVO(命名返回值优化)的结果。
#include <iostream>
using namespace std;
class A
{
public:
int x;
A()
{
cout << "default constructor" << endl;
x = 1;
}
A(int x)
{
cout << "constructor with param = " << x << endl;
this->x = x;
}
~A() {
cout << "destructor" << endl;
}
void print() {
cout << x << endl;
}
};
A fun() {
A a = A(10);
return a;
}
int main()
{
A a = fun();
return EXIT_SUCCESS;
}
默认 g++ 编译器:
constructor with param = 10
destructor
如果我们关闭 NRVO:g++ test.cpp -fno-elide-constructors
constructor with param = 10
destructor
destructor
destructor
destructor
老师希望我们通过引用传递来复制NRVO(命名返回值优化)结果。
语法a.A::A(10);
不正确。
构造函数用于创建类的对象,不能在已经存在的对象上调用它。即使是构造函数也不能显式调用。它由编译器隐式调用。
构造函数没有名称。
因此,您不能显式调用构造函数。当创建该类类型的对象时,编译器将自动调用构造函数。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句