c++ - 类实例化语法

标签 c++ constructor instantiation standards parentheses

我一直被教导说

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); and Class c = arg; are two totally equivalent statements, but look at this situation.

事实证明它们并不等同。第一个从 arg 构造出 Class c,而第二个则从 arg 构造出 Class > 然后复制构造 Class c 。请注意,实现可以省略该拷贝,而且通常会这样做。

Left l = Right(0);

这需要从 RightIntermediary 的转换,以及从 IntermediaryLeft 的转换。标准不允许这两个连续的用户定义转换,您必须至少明确执行其中一个转换,如下所示:

Left l = (Intermediary)Right(0);

关于c++ - 类实例化语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7936252/

相关文章:

php - 实例化一个对象而不在 PHP 中调用它的构造函数

c++ - 如何实例化一个只知道其名称的对象?

c++ - 修改XML文件QXMLStreamReader/Writer

c++ - 在 C++ 中打印 std::unordered_multimap 中特定键的多个值

c# - 什么时候以及为什么我应该使用 ClassName : this(null)?

javascript - Javascript 构造函数失败

c++ - 如何区分参数为非嵌套和嵌套 initializer_list 的两个重载函数?

java - Android:尝试实例化一个类

c++多个条件以匹配确切的字符串

c++ - 将引用从 Python 传递给用 swig 包装的 c++ 函数以获得返回值