【发布时间】:2011-01-19 04:09:12
【问题描述】:
我认为构造函数控制初始化,而 operator= 函数控制 C++ 中的赋值。那么为什么这段代码有效呢?
#include <iostream>
#include <cmath>
using namespace std;
class Deg {
public:
Deg() {}
Deg(int a) : d(a) {}
void operator()(double a)
{
cout << pow(a,d) << endl;
}
private:
int d;
};
int
main(int argc, char **argv)
{
Deg d = 2;
d(5);
d = 3; /* this shouldn't work, Deg doesn't have an operator= that takes an int */
d(5);
return 0;
}
在主函数的第三行,我将int 分配给Deg 类的对象。由于我没有operator=(int) 函数,我认为这肯定会失败……但它调用了Deg(int a) 构造函数。那么构造函数也控制赋值吗?
【问题讨论】:
标签: c++ class initialization operator-overloading