为什么这个语句不调用构造函数 - C ++ [英] Why this statement does not call the constructors - C++

查看:140
本文介绍了为什么这个语句不调用构造函数 - C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

模板类和普通类:

template <typename Type>
class Holder
{
public:
    Holder(const Type& value) : held_(value)
    {
        cout << "Holder(const Type& value)" << endl;
    }
    Type& Ref() { return held_; }
private:
    Type held_;
};

class Animal
{
public:
    Animal(const Animal& rhs) { cout << "Animal(const Animal& rhs)" << endl; }
    Animal() { cout << "Animal()" << endl; }
    ~Animal() { cout << "~Animal" << endl; }
    void Print() const { cout << "Animal::Print()" << endl; }
};

然后我想实例化 Holder< Animal> 与此语句 Holder< Animal> a(Animal()); ,但是,它失败。我的意思是 Animal()不被当作一个临时对象。此语句不调用 Holder 的构造函数。

Then I want to instantiate a Holder<Animal> with this statement Holder<Animal> a(Animal());, however, it fails. I mean Animal() is not treated as a temporary object. And this statement doesn't call Holder's constructor.

如果有人可以解释?我不清楚。我猜在 a 成为类型。然后,我使用 Holder< Animal> a = Holder< Animal>(Animal()); ,它工作得很好。所以,这里有一些情况:

If someone could explain? I'm not clear. I'm guessing a becomes a type here. Then, I use Holder<Animal> a = Holder<Animal>(Animal());, it works well. So, there are some cases here:


  1. Holder< Animal> a(Animal()); a.Ref()。Print(); // error

  2. Holder< Animal> a = Holder< Animal>(Animal()); a.Ref()。Print(); // ok

  3. Holder< int> b(4); b.Ref()= 10; cout < b.Ref()<< endl; // ok

  1. Holder<Animal> a(Animal()); a.Ref().Print(); // error
  2. Holder<Animal> a = Holder<Animal>(Animal()); a.Ref().Print(); // ok
  3. Holder<int> b(4); b.Ref() = 10; cout << b.Ref() << endl; //ok

可以解释一下吗?我只是有点困惑的第一个声明。和此语句导致的错误信息:

Can explain? I'm just a little confused with the first statement. And the error information this statement causes:

GCC4.7.2 错误:成员'Ref'in'a',属于非类型'Holder< Animal>(Animal(*)())'

VS10 错误C2228:.Ref的左边必须有class / struct / union error C2228:'.Print'的左侧必须有类/ struct / union

推荐答案

语句 Holder< Animal> a(Animal()); 不创建变量,而是声明一个返回 Holder< Animal> 的函数,参数。它通常被称为最烦琐的解析,因为这种模糊性(人们期望一个变量而不是一个函数声明)。

The statement Holder<Animal> a(Animal()); does not create a variable, but declares a function that returns a Holder<Animal> and that takes a function in parameter. It's usually called the most vexing parse, because of this ambiguity (that one would expect a variable rather than a function declaration).

Herb Sutter解释了不同的可能语法这里。在C ++ 11中,一个可能的解决方案是:

Herb Sutter explains the different possible syntaxes here. In C++11, a possible solution is:

auto a = Holder<Animal> {};

这篇关于为什么这个语句不调用构造函数 - C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆