嗨我有这个ostream运算符,在编译时给出了这个错误:cannot access private member declared in class 'CService'
这是我的代码:
friend ostream& operator <<(ostream& os, CService &obj);
ostream& operator<<(ostream &os, CService &obj) {
os<<obj.m_strClient;
return os;
}
我尝试返回ostream&
,但这不能解决问题,而是增加了另一个错误syntax error : ';'
这是我的整个代码:
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
class CService {
private:
string m_strClient;
string m_strSeller;
int m_iMinutes;
public:
CService() {
m_strClient="N/A";
m_strSeller="N/A";
m_iMinutes=0;
}
CService( string c, string s, int m ) {
m_strClient=c;
m_strSeller=s;
m_iMinutes=m;
}
CService(const CService &obj ) {
m_strClient=obj.m_strClient;
m_strSeller=obj.m_strSeller;
m_iMinutes=obj.m_iMinutes;
}
string GetClient() {
return m_strClient;
}
string GetSeller() {
return m_strSeller;
}
int GetMusic() {
return m_iMinutes;
}
CService CService::operator =(CService obj) {
m_strClient=obj.m_strClient;
m_strSeller=obj.m_strSeller;
m_iMinutes=obj.m_iMinutes;
return *this;
}
bool operator < (const CService &obj) const {
return m_strSeller<obj.m_strSeller;
}
CService CService::operator +(const CService &obj) const {
return CService( m_iMinutes+obj.m_iMinutes );
}
friend ostream& operator <<(ostream& os, CService &obj);
bool CService::operator==(CService &obj) {
return (obj.m_strSeller==m_strSeller);
}
};
ostream& operator<<(ostream &os, CService &obj) {
os<<obj.m_strClient;
return ostream&;
}
答案 0 :(得分:0)
你有很多问题,主要问题是:
return os;
代替return ostream&;
您还没有接受int
的构造函数:添加CService(int m = 0)
您不应在课程定义中添加CService::
:将其删除
我更正了它们( Live code ),至少它会被编译而没有错误:
class CService
{
private:
string m_strClient;
string m_strSeller;
int m_iMinutes;
public:
CService(int m = 0)
{
m_strClient = "N/A";
m_strSeller = "N/A";
m_iMinutes = m;
}
CService(string c, string s, int m)
{
m_strClient = c;
m_strSeller = s;
m_iMinutes = m;
}
CService(const CService &obj)
{
m_strClient = obj.m_strClient;
m_strSeller = obj.m_strSeller;
m_iMinutes = obj.m_iMinutes;
}
string GetClient()
{
return m_strClient;
}
string GetSeller()
{
return m_strSeller;
}
int GetMusic()
{
return m_iMinutes;
}
CService operator =(CService obj)
{
m_strClient = obj.m_strClient;
m_strSeller = obj.m_strSeller;
m_iMinutes = obj.m_iMinutes;
return *this;
}
bool operator<(const CService &obj) const
{
return m_strSeller < obj.m_strSeller;
}
CService operator +(const CService &obj) const
{
return CService(m_iMinutes + obj.m_iMinutes);
}
friend ostream& operator <<(ostream& os, CService &obj);
bool operator==(CService &obj)
{
return (obj.m_strSeller == m_strSeller);
}
};
ostream& operator<<(ostream &os, CService &obj)
{
os << obj.m_strClient;
return os;
}