定义string类型 编译器还是报错

今天遇到一个有趣的代码

#include<iostream>
#include<map>
//#include<string.h>
using std::cout;
using std::string;
using std::endl;
using std::pair;
int main()
{   string A;//A
   pair <string,string> my_name("yi","dong");
   cout<<"my name is "<<my_name.first<<" ";
   cout<<my_name.second<<"."<<endl;
   return 0;
}

当去掉using std::string换成#include<string.h>时编译器报错了。
the value of ‘string’ is not usable in a constant expression
注释其他代码,main仅剩string A时编译器也出错了


#include <string>
将string库包含到当前编译单元中.

using std::string;

#include<iostream>
using namespace std;
int main()
{
    string test("test");
    cout<<test<<endl;
    return 0;
}

编译这个代码,编译器没有出错

当我们改成下面这个代码,也就是没有引用string

#include<iostream>
using std::cout;
using std::endl;
int main()
{
    string test("test");
    cout<<test<<endl;
    return 0;
}
编译器提示如下
lishun@lishun-P43C-A7:~$ g++ 44.cpp -std=c++11 -o p
44.cpp: In function ‘int main()’:
44.cpp:6:5: error: ‘string’ was not declared in this scope
     string test("test");
     ^
44.cpp:6:5: note: suggested alternatives:
In file included from /usr/include/c++/5/iosfwd:39:0,
                 from /usr/include/c++/5/ios:38,
                 from /usr/include/c++/5/ostream:38,
                 from /usr/include/c++/5/iostream:39,
                 from 44.cpp:1:
/usr/include/c++/5/bits/stringfwd.h:74:33: note:   ‘std::__cxx11::string’
   typedef basic_string<char>    string;   
                                 ^
/usr/include/c++/5/bits/stringfwd.h:74:33: note:   ‘std::__cxx11::string’
44.cpp:7:11: error: ‘test’ was not declared in this scope
     cout<<test<<endl;
           ^
lishun@lishun-P43C-A7:~$ 
当我加上using std::string;
#include<iostream>
using std::cout;
using std::endl;
using std::string;
int main()
{
    string test("test");
    cout<<test<<endl;
    return 0;
}

编译器能通过

再看看这个代码

#include<iostream>
#include<string>
using std::cout;
using std::endl;
int main()
{
    string s("c++");
    cout<<s<<endl;
    return 0;
}
编译器也没有通过


编译单元包含了string

必须使用string才能通过编译器

使用就是string样式 std::string;或者using namespace std;或者 using std::string;

只是中间的引用string类型较为隐蔽,不容易发现。不用using namespace std时才容易出错


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值