visual c++重载输入运算符使用不同的头文件编译通不过
#include <iostream.h>
#include <string.h>
#include <stdlib.h>
//#include <iostream>
//using namespace std;
class String
{
int size; // string size
char *str; // start of internal string
void set(const char* s); // private string allocation
public:
friend istream& operator > > (istream& in, String& s);
String (const char* s = " ") // default and conversion
{
set(s);
}
String (const String &s) // copy constructor
{
set(s.str);
}
~String() // destructor
{
delete [ ] str;
}
String& operator = (const String& s); // assignment
char* get () const // return pointer to start
{
return str;
}
} ;
void String::set(const char* s)
{
size = strlen(s); // evaluate size
str = new char[size + 1]; // request heap memory
if (str == 0)
{
cout < < "Out of memory\n "; exit(0);
}
strcpy(str,s);
} // copy client data to heap
String& String::operator = (const String& s)
{
if (this == &s) return *this; // no work if self-assignment
delete [ ] str; // return existing memory
set(s.str); // allocate/set new memory
return *this;
} // to support chain assignment
istream& operator > > (istream& in, String& s) // global friend
{
char name[80]; // local storage for data
in > > name; // accept data
delete [] s.str; // return existing memory
s.set(name); // allocate/init new memory
return cin;
} // important for chain work
int main ()
{
String s; int qty; // local variables
cout < < "Enter customer name and quantity: ";
cin > > s > > qty; // accept name, quantity
//operator> > (cin,s);
//cin> > qty;
cout < < "The customer name is: ";
cout < < s.get() < < endl; // using public methods
cout < < "Quantity ordered is: ";
cout < < qty < < endl;
return 0;
}
以上代码如果把包含头文件
#include <iostream.h> 注释掉,
换成
#include <iostream>
using namespace std;
则编译通不过,出现D:\c#\overwritein\overwritein.cpp(56) : error C2248: 'str ' : cannot access private member declared in class 'String '
D:\c#\overwritein\overwritein.cpp(10) : see declaration of 'str '
D:\c#\overwritein\overwritein.cpp(57) : error C2248: 'set ' : cannot access private member declared in class 'String '
D:\c#\overwritein\overwritein.cpp(11) : see declaration of 'set '
D:\c#\overwritein\overwritein.cpp(65) : error C2593: 'operator > > ' is ambiguous的错误提示。已经安装了sp6补丁。
[解决办法]
class String
{
int size; // string size
char *str; // start of internal string
void set(const char* s); // private string allocation
…………
这样的语法(没有public:private:protected的数据成员)告诉编译器的就是你的东西是private的,而error C2248: 'str ' : cannot access private member declared in class 'String '
说明访问了私有成员
还有尽量不要用string 这种标准里已经有的名字
造成
以上代码如果把包含头文件
#include <iostream.h> 注释掉,
换成
#include <iostream>
using namespace std;
的问题原因就在此
#include <iostream>
包含标准文件
using namespace std;
系统发现有string 的定义在std里,而又在外面定义一个,产生模棱两可的问题“ambiguous的错误提示”
记住:总是让编译器明白你到底要干什么,不要给非标准的东西机会,更不要模棱两可
[解决办法]
编译器的问题.换一个试试看
[解决办法]
VC6编译器的问题,使用VC8 就没问题的
