gpt4 book ai didi

c++ - 为什么不编译?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:05:50 24 4
gpt4 key购买 nike

当我尝试使用第一种形式声明 iss 时,g++ 给出“错误:‘iss >> s’中的‘operator>>’不匹配”。但是这两个不同的声明不是做同样的事情吗?

#include <iostream>
#include <sstream>
#include <string>


int main() {
const char *buf = "hello world";
std::string ss(buf);
//std::istringstream iss(std::string(buf)); // this doesn't work
std::istringstream iss(ss); // but this does
std::string s;
iss >> s;
}

最佳答案

这被称为 C++ 的“最令人烦恼的解析”:在您看来像实例声明的内容在编译器看来实际上像函数声明。

std::string name(); //function declaration
std::string name; //object declaration with default constructor

std::stringstream ss(std::string(buf)); //function declaration
std::stringstream ss(std::string buf); //another function declaration
std::stringstream ss(std::string); //also a function declaration
std::stringstream ss(std::string()); //ditto, argument names are optional

std::stringstream ss((std::string(buf))); //object declaration

请注意最后一个示例中的额外括号。这些括号在函数声明中是不合法的。

第一个带有默认构造函数的例子是众所周知的。在第二种情况下增加的不确定性是 C++ 中参数名称周围的括号是合法的但可选的。例如,您可以像这样定义一个函数:

void foo(int (bar))
{}

基本上每次当构造函数的所有参数都是采用 0 或 1 个参数的构造函数调用的临时参数时,您都会遇到这种情况,快速的解决方案是在其中一个参数周围加上额外的括号。

关于c++ - 为什么不编译?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1854251/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com