我不清楚在如下所示的表达式中,临时变量是否采用 const 类型。
#include <iostream>
class X {
public:
X(int a) { i = a; cout << "X(int) [" << (int)this << "]" << endl; }
X& operator+(const X& x)
{
i += x.i;
cout << "X operator+(const X&) [" << (int)this << "]" << endl;
return *this;
}
~X() { cout << "~X [" << (int)this << "]" << endl; }
private:
int i;
};
int main()
{
X x = X(3) + X(4);
cout << "done" << endl;
return 0;
}
X(3)
表现得像非常量(因为我可以调用 operator+
,而 X(4)
表现得像 const(因为,它需要 operator+
中的 const 参数。
谁能澄清一下,什么是正确的理解?
最佳答案
当涉及到类类型时,当您创建一个 const 类型的临时对象时,该临时对象将是 const。当您创建一个非常量类型的临时文件时,该临时文件将是非常量的。就是这样。 IE。就确切的类型而言,const 和 temporaries 之间根本没有联系。临时类类型从不假定 const 本身。是你可以明确地对其施加 const。
在您的示例中,X(3)
和 X(4)
都不是常量。由于 X(3)
不是 const,您可以在其上调用非常量方法。
说您的 X(4)
“表现为常量”是不正确的。没有任何迹象表明它在您的示例中“表现为常量”。仅仅因为您能够用某物初始化一个 const 引用并不意味着该某物是 const。
在您的问题中,您声明“需要 operator+
中的 const 参数”。那是不正确的。您的 operator+
中不需要 const argument。您的参数 x
被声明为常量引用。 const 引用可以很容易地绑定(bind)到 const 参数以及非 const 参数。在您的情况下,const 引用参数 x
绑定(bind)到非常量临时参数 X(4)
。
关于c++ - 临时对象不表现为 const,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8149094/