【问题标题】:C++ Successful compilation without inclusion of <string> header [duplicate]C ++成功编译,不包含<string>标头[重复]
【发布时间】:2016-11-20 08:07:05
【问题描述】:

我注意到我设法编译了以下代码,但不包含 &lt;string&gt;。它不应该给我一个错误吗?

#include <iostream>
 using namespace std;

struct Sales_data {
    string book_no;
    double units_sold;
    double price;
};

int main() {
    Sales_data book1, book2;
    cout << "Please enter first transaction in format: ISBN, units sold & price" << endl;
    cin >> book1.book_no >> book1.units_sold >> book1.price;
    cout << "Please enter second transaction in format: ISBN, units sold & price" << endl;
    cin >> book2.book_no >> book2.units_sold >> book2.price;

    cout << "******************************" << endl;
    cout << "Total units sold = " << book1.units_sold + book2.units_sold << endl;
    cout << "Total revenue = " << (book1.units_sold * book1.price) + (book2.units_sold * book2.price) << endl;
    return 0;
}

编译结果:

[yapkm01][~/C++Primer/chapter2]# g++ -std=c++11 -o 2-41a 2-41a.cc
[yapkm01][~/C++Primer/chapter2]#

【问题讨论】:

  • iostream 显然在您的标准库实现中包含string。这是偶然的——包括你知道你需要的东西。
  • "[yapkm01][~/C++Primer/chapter2]# g++ " - 为什么要以 root 身份编译代码?没关系(很多),只是好奇..
  • @JesperJuhl 不,我没有以 root 身份编译。我正在使用我的 id "yapkm01" 进行编译。
  • @yapkm01 问题中的井号 (#) 提示另有说明;-) "#" 用于 root 用户,普通用户通常会得到 "$"。 "[yapkm01][~/C++Primer/chapter2]# g++ ..."

标签: c++ c++11


【解决方案1】:

应该#include &lt;string&gt;,否则您无法保证std::string 的原型可用。

但是,您似乎没有这样做,因为显然,在您的情况下,在您的实现中,iostream 标头似乎包含了您的字符串(直接或间接)。但是,您不能依赖它。

始终包含您使用的内容。不这样做依赖于实现定义的行为并且不可移植。

【讨论】:

    【解决方案2】:

    不应该给我一个错误吗?

    它依赖于实现。一些编译器实现本质上是 #include &lt;string&gt; 带有 &lt;iostream 标头,其他编译器实现具有前向声明。

    始终包含您使用的任何标准类型的标题。多个#include 语句没有害处,并且已经使用适当的标头保护进行了优化。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-27
      • 1970-01-01
      • 2014-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多