没有包含string的后果

写了一个很简单的程序:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string user_name;
 
 cout << "Please enter your name:";
 cin >> user_name;
 cout << "/nHello, " << user_name << " ... and goodbye!/n";

 return 0;
}

注释掉string库时,产生了如下的一些错误:

e:/cppprogram/hello.cpp/hello.cpp.cpp(14) : error C2679: binary '>>' : no operator defined which takes a right-hand operand of type 'class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >' (or there is no acceptable conversion)

e:/cppprogram/hello.cpp/hello.cpp.cpp(15) : error C2679: binary '<<' : no operator defined which takes a right-hand operand of type 'class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >' (or there is no acceptable conversion)

在MSDN上找了一下error 2679,但没结果!另外这点说明'<<'操作符的一些什么问题呢?

接着将using namespace std;也注释掉,结果更是大吃一惊:

E:/CPPProgram/hello.cpp/hello.cpp.cpp(8) : error C2065: 'string' : undeclared identifier
E:/CPPProgram/hello.cpp/hello.cpp.cpp(8) : error C2146: syntax error : missing ';' before identifier 'user_name'
E:/CPPProgram/hello.cpp/hello.cpp.cpp(8) : error C2065: 'user_name' : undeclared identifier
E:/CPPProgram/hello.cpp/hello.cpp.cpp(10) : error C2065: 'cout' : undeclared identifier
E:/CPPProgram/hello.cpp/hello.cpp.cpp(10) : error C2297: '<<' : illegal, right operand has type 'char [24]'
E:/CPPProgram/hello.cpp/hello.cpp.cpp(11) : error C2065: 'cin' : undeclared identifier
E:/CPPProgram/hello.cpp/hello.cpp.cpp(11) : warning C4552: '>>' : operator has no effect; expected operator with side-effect
E:/CPPProgram/hello.cpp/hello.cpp.cpp(12) : error C2297: '<<' : illegal, right operand has type 'char [9]'

其实对于namespace,一直心存疑问:他是不是就是一段内存块的标志呢?

又将main 改为my_main后,更是大吃两惊了——编译竟然没错误!进而连接已编译程序,错误出现了:
LIBCD.lib(crt0.obj) : error LNK2001: unresolved external symbol _main
Debug/hello.cpp.exe : fatal error LNK1120: 1 unresolved externals

这让我想到了C++程序的编译模式,它是先编译后连接!在编译期间,编译器以为此程序只是一个模块而已,因此对改变无动于衷!然而连接器就不同意了,它无法找到程序的入口——错误也因此应运而生!

对于以上的错误和警告,我得一一搞清楚才是!

================================================

看了一些书,对以上的问题有所了解了:

原来,C++中的输出操作符“<<”和输入操作符“>>”是要重载的!不同的类需要重载这些操作符,包括:"=", ">", "<"…………

如果重载的是输出操作符<<,第1个参数是对流ostream类的引用,第2个参数是对要定义的输入/输出类的引用,当然,也可以是该类的指针。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值