在课堂中使用返回值

using return value in class

本文关键字:返回值 课堂      更新时间:2023-10-16

标题文件

#ifndef deneme_h
#define deneme_h
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
using namespace std ;
class A
{
public:
Course ( int code ) ;
int getACode () ;

 private:
    int code   ;
};

class B
{
  public:
    B ( A * a  = NULL) ;
        A     * getA     () ;
 private:
    A     * a   ;
  friend ostream & operator<< ( ostream & out , B & b ) ;
};
#endif

A.CPP

#include "deneme.h"
using namespace std ;

A :: A ( int code )
{
    this -> code = code;
} 
int A :: getACode()
{
    return this -> code;
}

B.CPP

#include "deneme.h"
using namespace std ;
B::B ( A     * a ) 
    {
        this -> a = new A(223);
        this -> a = a;
    }
A * A::getA     ()  {   return this -> a;}

ostream & operator<< ( ostream & out , B & b ) { out << b.course->getACode();}

和main.cpp

#include "deneme.h"
using namespace std;
int main(){
Course* c1 = new Course(223) ;
Offering* o1_1 = new  Offering(c1);
cout<< *o1_1;
return 0;
}

大家好

我想询问此代码。上面的代码正常运行,并打印223。但是,当我更改操作员时,b.cpp中的零件过载

 ostream & operator<< ( ostream & out , Offering & offering ) { out << offering.(getCourse() )->getCourseCode();}

我有一个错误。为什么会出现错误?我不能使用返回值。感谢您的答案。

正如已经说过的,您需要返回,我认为您想要的行是:

ostream & operator<< ( ostream & out , Offering & offering ) { out << ( offering.getCourse() )->getCourseCode(); return out; }

(我移动了一个括号)

删除getCourse()

周围的括号

与iostream一起使用时:

operator<<应通过const reference进行第二个参数(如果这很微不足道)。

它应该返回其第一个参数。

so

ostream & operator<< ( ostream & out , const B & b ) 
{ 
     return out << b.course->getACode();
} 
ostream & operator<< ( ostream & out , const Offering & offering ) 
{ 
    return out << offering.getCourse()->getCourseCode();
} 

在两种情况下其他语句之后,您也可以将return out作为单独的语句。

还请注意,在C 中,您不必使用新对象创建所有对象。