C++ 中的赋值与初始化
我认为 C++ 中构造函数控制初始化,operator= 函数控制赋值。那么为什么这段代码可以工作呢?
#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;
}
在 main 函数的第三行,我将一个 int
分配给 Deg
类的对象。由于我没有 operator=(int)
函数,我认为这肯定会失败......但它调用了 Deg(int a)
构造函数。那么构造函数也控制赋值吗?
I thought that constructors control initialization and operator= functions control assignment in C++. So why does this code work?
#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;
}
On the third line of the main function, I am assigning an int
to an object of class Deg
. Since I don't have an operator=(int)
function, I thought that this would certainly fail...but instead it calls the Deg(int a)
constructor. So do constructors control assignment as well?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这就是所谓的隐式类型转换。编译器将查看是否有一个构造函数可以直接从您分配的类型更改为您尝试分配的类型,并调用它。您可以通过在您不希望隐式调用的构造函数前面添加
explicit
关键字来阻止这种情况发生,如下所示:explicit Deg(int a) : d(a) {}
This is what's called implicit type conversion. The compiler will look to see if there's a constructor to directly change from the type you're assigning to the type you're trying to assign, and call it. You can stop it from happening by adding the
explicit
keyword in front of the constructor you wouldn't like to be implicitly called, like this:explicit Deg(int a) : d(a) {}
只是为了澄清 JonM 的答案:
对于
d = 3
行,涉及赋值运算符。正如 JonM 所说,3
被隐式转换为Deg
,然后该Deg
被分配给d
使用编译器生成的赋值运算符(默认情况下执行按成员赋值)。如果你想阻止赋值,你必须声明一个私有赋值运算符(并且不实现它):Just to clarify JonM's answer:
For the line
d = 3
, an assignment operator is involved.3
is being implicitly converted to aDeg
, as JonM said, and then thatDeg
is assigned tod
using the compiler-generated assignment operator (which by default does a member-wise assignment). If you want to prevent assignment, you must declare a private assignment operator (and do not implement it):