在构造函数中将临时变量传递给引用arg。但不适用于一般的功能。为什么? [英] passing Temporary variables to reference arg in Constructor works. but not for functions in general. Why?

查看:162
本文介绍了在构造函数中将临时变量传递给引用arg。但不适用于一般的功能。为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑下面的代码。

这里,A a(B())编译,即使构造函数是A(B& b);
但是打印(B())不工作。但是打印也声明为print(B& b);
为什么会出现这种不一致?

Consider the following code.
Here, A a(B()) compiles even though the constructor is A(B& b); But print(B()) does not work. But print is also declared as print(B& b); Why this inconsistency?

#include <iostream>
using namespace std;

class B{
    public:
            char b;
};

class A {
    public:
            B b;
            A(B& b);
            A() { }
};

A::A(B& b) {
    this->b = b;
}

void print(B& b) { }

int main(){
    print(B());
    A a(B());
}


推荐答案

A 的实例。它声明一个名为函数,它返回一个 A 并接收一个未命名的类型参数指针到函数返回B。因为它只是一个声明,它编译。如果您在代码的其他地方引用 a ,则会遇到其他问题。为什么这是一个函数声明而不是一个对象定义,查找的术语是最烦琐的解析

It compiles because it's not creating an instance of A. It's declaring a function named a that returns an A and receives one unnamed parameter of type pointer-to-function-returning-B. Since it's just a declaration, it compiles. If you're referred to a elsewhere in the code, you'd have seen additional problems. For why that's a function declaration instead of an object definition, the term to look up is most vexing parse.

这篇关于在构造函数中将临时变量传递给引用arg。但不适用于一般的功能。为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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