注册 登录
编程论坛 C++教室

谁能帮我看看啊?关于 运算符重载的问题

沙漠的行者 发布于 2011-06-22 16:14, 367 次点击
#ifndef PH_H
#define PH_H

#include <iostream>
using std::istream;
using std::ostream;

#include <string>
using std::string;

class AM
{
    friend ostream& operator<<(ostream &,const AM &);
    friend istream& operator>>(istream &,AM &);
private:
    string a;
};
#endif
#include <iomanip>
using std::setw;
#include "ph.h"
ostream &operator<<(ostream &put,AM &l)
{
    put<<l.a<<endl;
    return put;
}
istream &operator>>(istream &get,AM &l)
{
    get.ignore();
    get>>setw(3)>>l.a;
    return get;
}
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
#include "ph.h"
int main()
{
    AM ha;
    cin>>ha;
    cout<<ha<<endl;
    return 0;
}
结果却是::\c++\microsoft visual studio\myprojects\dfgdf\df.cpp(21) : fatal error C1083: Cannot open include file: 'ph.h': No such file or directory
???
3 回复
#2
ToBeStronger2011-06-23 12:52
楼主我帮你程序改了改,发现几个错误,put<<l.a<<endl;改成put<<l.a<<std::endl;
friend ostream& operator<<(ostream &,const AM &);
应该吧const去掉,应为赋值操作修给了string a,所以不能定义const;
ph.h代码
#ifndef PH_H
#define PH_H

#include <iostream>
using std::istream;
using std::ostream;

#include <string>
using std::string;

class AM
{
    friend ostream& operator<<(ostream &,AM &);
    friend istream& operator>>(istream &,AM &);
private:
    string a;
};
#endif

ph.cpp 代码
#include <iomanip>
using std::setw;
#include "ph.h"
ostream &operator<<(ostream &put,AM &l)
{
    put<<l.a<<std::endl;
    return put;
}
istream &operator>>(istream &get,AM &l)
{
    get.ignore();
    get>>setw(3)>>l.a;
    return get;
}

main函数代码

#include <iostream>
using std::cin;
using std::cout;
using std::endl;
#include "ph.h"
int main()
{
    AM ha;
    cin>>ha;
    cout<<ha<<endl;
    return 0;
}
运行应该能成功
#3
jbd05132011-06-24 16:48
没看懂!
#4
ToBeStronger2011-06-25 01:08
回复 3楼 jbd0513
其实是重载输入输出操作符........
1