【问题标题】:What is the meaning of the address symbol & in a constructor?构造函数中地址符号 & 的含义是什么?
【发布时间】:2019-04-15 10:36:14
【问题描述】:

我正在查找 c++ 库,并查看 istream 类,我对带有地址符号的承包商感到困惑。带地址符号的构造函数是什么意思?

istream 构造函数之一是。

protected: iostream& (iostream&& x);

我在网站 cplusplus.com 上找到的,

链接:iostream



我定义了一个带有 & 符号的类似构造函数的客户类:

//Test.cpp
#include <iostream>/*cout,cin*/
#include <typeinfo>/*typeid(),name()*/
using namespace std;
struct MyTest{
                MyTest&(double b){}
};
int main(int argc,char* argv[]){
        MyTest mt2(2.1);
        cout << typeid(mt2).name() << endl;
return 0;
}

我使用下面的命令来编译它:

g++ Test.cpp -o Test -std=c++11

但是,我收到一些编译错误消息:

Test.cpp:7:11: error: expected unqualified-id before ‘float’
   MyTest&(float b){}
           ^
Test.cpp:7:11: error: expected ‘)’ before ‘float’
Test.cpp:7:10: error: expected ‘;’ at end of member declaration
   MyTest&(float b){}
          ^
Test.cpp:7:17: error: expected ‘;’ at end of member declaration
   MyTest&(float b){}
                 ^
Test.cpp:7:18: error: expected unqualified-id before ‘)’ token
   MyTest&(float b){}
                  ^
Test.cpp: In function ‘int main(int, char**)’:
Test.cpp:12:16: error: no matching function for call to ‘MyTest::MyTest(double)’
  MyTest mt2(2.1);


我很困惑,c++ 库 istream 类很好。为什么我的自定义类构造函数失败了?我错过了什么?

【问题讨论】:

  • 你在哪里找到iostream&amp; (iostream&amp;&amp; x);?你能链接到repo中的确切位置吗?
  • 尽管名称和它的谷歌排名,cplusplus.com 不是权威的,甚至不是好的来源。它有很多错误。
  • C++ 有一个上下文相关的语法;您要问的不是 address-of 运算符,而是 reference type-modifier。
  • 我不知道为什么投反对票。这是一个关于在文档中找到的东西的完全合理的问题;并且 OP 试图重现语法以了解它将做什么但失败了。修复google排名/cplusplus.com是社区的失败;而不是阅读它的OP;并要求了解错误是一件好事。

标签: c++ constructor symbols


【解决方案1】:

cplusplus.com 上的信息……有时并不可靠。 (有关此问题的讨论,请参阅 What's wrong with cplusplus.com?。)在 CPPReference 上,您可以看到移动构造函数只是一个普通的移动构造函数。

【讨论】:

    【解决方案2】:

    这是http://www.cplusplus.com/reference/istream/iostream/iostream/ 中的一个错误。

    如果你看https://en.cppreference.com/w/cpp/io/basic_iostream/basic_iostream,你会发现

    受保护:basic_iostream(basic_iostream&& other);

    【讨论】:

    • 鉴于 cplusplus.com 网站声明:copy (2) iostream&amp; (const iostream&amp;) = delete; move (3) protected: iostream&amp; (iostream&amp;&amp; x); 我认为您需要澄清您认为错误的部分
    猜你喜欢
    • 2015-12-29
    • 2016-12-15
    • 1970-01-01
    • 2015-11-03
    • 2023-01-25
    • 2010-12-08
    • 2020-04-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多