我一直被教导说
1. Class c(arg);
和
2. Class c = arg;
是两个完全等价的语句,但看看这个情况。
#include <iostream>
class Intermediary {
};
class Left {
public:
Left(const Intermediary &) {
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
};
class Right {
public:
// The argument is there just so that the example can work, see below
Right(int) {
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
operator Intermediary () const {
std::cout << __PRETTY_FUNCTION__ << std::endl;
return Intermediary();
}
};
现在如果我这样做:
Left l = Right(0);
编译器会提示
error: conversion from Right to non-scalar type Left requested
但是如果我这样做:
Left l(Right(0));
然后一切都会编译并输出
Right::Right(int)
Right::operator Intermediary() const
Left::Left(const Intermediary&)
但是,如果我这样做:
Left l = (Intermediary)Right(0);
然后一切都会再次编译,输出就像上面的一样。
很明显
1. Class c(arg);
和
2. Class c = arg;
不一样,但是为什么不一样,有什么区别呢?我在网上找不到任何相关信息。
最佳答案
I've always been taught that
Class c(arg);
andClass c = arg;
are two totally equivalent statements, but look at this situation.
事实证明它们并不等同。第一个从 arg
构造出 Class c
,而第二个则从 arg
构造出 Class
> 然后复制构造 Class c
。请注意,实现可以省略该拷贝,而且通常会这样做。
Left l = Right(0);
这需要从 Right
到 Intermediary
的转换,以及从 Intermediary
到 Left
的转换。标准不允许这两个连续的用户定义转换,您必须至少明确执行其中一个转换,如下所示:
Left l = (Intermediary)Right(0);
关于c++ - 类实例化语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7936252/