如何在C ++中返回引用 [英] How to return a reference in C++

查看:99
本文介绍了如何在C ++中返回引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果例如我在一个函数中创建一个新对象,并且我想返回它的引用怎么做呢?



我想说,我有一个IntClass私人中的int num字段。所以我想在函数中创建一个新的IntClass元素,并返回该对象的引用。我试过这样的东西,但似乎是非法的(从某种原因,当我做这样的事情时,二进制文件被删除,当我编译代码,虽然我没有从编译器本身(ECLIPSE)的错误:

  IntClass * a = new IntClass(10); 
IntClass& ref = * a;
return ref; / code>



任何想法如何返回参考?



它允许假设C + +使用垃圾收集



因为不清楚你大多数为什么我想做这里是完整的问题:



我有这个文件(不是由我做的,不能编辑):



poly_subtype.h

$ :

  #ifndef POLY_SUBTYPE_H 
#define POLY_SUBTYPE_H
#include< ; iostream>
#includecpu_add.h
使用std :: cout;
使用std :: endl;

//派生类定义
class IntClass;
class DoubleClass;

//虚拟数字类IntClass和FloatClass将从这个类派生。
class Number {
public:
//返回一个Number对象,它是x + this的结果,当x是DoubleClass时
virtual Number& addDouble(DoubleClass& x)= 0;

//返回一个Number对象,它是x + this的结果,当x是IntClass时
virtual Number& addInt(IntClass& x)= 0;

//返回一个Number对象,它是x + this的结果,当x是
// IntClass或DoubleClass
virtual Number& operator +(Number& x)= 0;

//打印存储在对象中的数字
virtual void print_number()= 0;
};

类IntClass:public Number {
private:
int my_number;
public:
//构造方法
IntClass(int n):my_number(n){}

//返回存储在对象中的数字
int get_number(){return my_number;}

//打印存储在对象中的数字
void print_number(){cout< my_number<< endl;}

//返回一个DoubleClass对象,它是x的结果+ this
Number& addDouble(DoubleClass& x);

//返回一个IntClass对象,它是x +的结果
Number& addInt(IntClass& x);

//返回一个Number对象,它是x + this的结果。
//返回对象的实际类取决于x。
//如果x是IntClass,那么结果如果IntClass。
//如果x是DoubleClass,那么结果是DoubleClass。
Number&运算符+(数字& x);
};

class DoubleClass:public Number {
private:
double my_number;
public:
//构造函数
DoubleClass(double n):my_number(n){}

//返回存储在对象中的数字
double get_number(){return my_number;}

//打印存储在对象中的数字
void print_number(){cout< my_number<< endl;}

//返回一个DoubleClass对象,它是x的结果+ this
Number& addDouble(DoubleClass& x);

//返回一个DoubleClass对象,它是x +的结果
Number& addInt(IntClass& x);

//返回一个DoubleClass对象,它是x + this的结果。
//如果x是IntClass或DoubleClass,这应该会工作
Number& operator +(Number& x);
};

#endif

我有这个文件



cpu_add.h:这是我写的,不能编辑 - 说我可以使用那些函数,

  #ifndef CPU_ADD_H 
#define CPU_ADD_H

double add_double_double(double a,double b ){return(a + b);}
double add_int_double(int a,double b){return((double)(a)+ b);}
int add_int_int(int a,int b) {return(a + b);}

#endif

是实现下一个函数(您可以在 poly_subtype.h 中找到它们的声明和功能):

  Number& IntClass :: addInt(IntClass& x); 
Number& IntClass :: addDouble(DoubleClass& x);
Number& IntClass :: operator +(Number& x);
Number& DoubleClass :: addInt(IntClass& x);
Number& DoubleClass :: addDouble(DoubleClass& x);
Number& DoubleClass :: operator +(Number& x);

我希望现在更清楚了。



例如 AddInt

  IntClass :: addInt(IntClass& x){
int num = add_int_int(my_number,x.get_number());
IntClass * a = new IntClass(num);
IntClass& ref = * a;
return ref;
}


解决方案

你上面写的,这是一个坏的窗台。如果一个资源在自由存储上分配,你应该返回一个指针,而不是一个引用。更好的是,使用适当类型的智能指针。 std :: auto_pointer (或更好 std / boost :: unique_ptr )如果资源不是由生产者持有, std :: shared_ptr 如果情况相反。您的代码示例是合法的,但返回引用的使用者不(也不能)知道如何处理返回的引用。



我可以想象在如下情况下返回对象的常量引用:

  class Producer {
std :: shared_ptr< SomeObject> mObject;

public:
Producer():mObject(new SomeObject){}

const SomeObject& GetObject()const {
return * mObject;
}

}

然而,你可以返回对静态持续时间的对象的引用,但它有一些缺点 - 没有(适当的)控制对象的生命周期,例如:

  SomeObject& GetSomeObjectSingletonReference(){
static SomeObject sInstance;
return sInstance;
}

干杯,



Paul


If for example I create a new object in a function and I want to return its reference how can I do it?

Lets say I got an IntClass that has a 'int num' field in the private. So i want to create a new element of IntClass in the function and return the reference of that object. I've tried something like that but it seems illegal (from some reason when I do such thing the Binaries gets deleted when I compile the code although I get no errors from the compiler itself (ECLIPSE):

 IntClass* a = new IntClass(10);
 IntClass &ref = *a;
 return ref;

Any ideas how to return a reference then?

EDIT: It's allowed to "assume" that C++ uses a Garbage-Collection

As it's not clear to most of you WHY I "want" to do it so here is the full question:

I got this file (Not made by me and can't be edited):

poly_subtype.h:

#ifndef POLY_SUBTYPE_H
#define POLY_SUBTYPE_H
#include <iostream>
#include "cpu_add.h"
using std::cout;
using std::endl;

//Deriving classes definition
class IntClass;
class DoubleClass;

//The Virtual Number Class. IntClass and FloatClass will derive from this class.
class Number {
    public:
        //return a Number object that's the results of x+this, when x is DoubleClass
        virtual Number& addDouble(DoubleClass& x) = 0;

        //return a Number object that's the results of x+this, when x is IntClass
        virtual Number& addInt(IntClass& x) = 0;

        //return a Number object that's the results of x+this, when x is either
        //IntClass or DoubleClass
        virtual Number& operator+(Number& x) = 0;

        //Print the number stored in the object
        virtual void print_number() = 0;
};

class IntClass : public Number {
    private:
        int my_number;
    public:
        //Constructor
        IntClass(int n):my_number(n) {}

        //returns the number stored in the object
        int get_number()  {return my_number;}

        //print the number stored in the object
        void print_number() {cout << my_number << endl;}

        //return a DoubleClass object that's the result of x+this
        Number& addDouble(DoubleClass& x);

        //return an IntClass object that's the result of x+this
        Number& addInt(IntClass& x);

        //return a Number object that's the result of x+this.
        //The actual class of the returned object depends on x.
        //If x is IntClass, then the result if IntClass.
        //If x is DoubleClass, then the results is DoubleClass.
        Number& operator+(Number& x);
};

class DoubleClass : public Number {
    private:
        double my_number;
    public:
        //Constructor
        DoubleClass(double n):my_number(n) {}

        //returns the number stored in the object
        double get_number()  {return my_number;}

        //Print the number stored in the object
        void print_number() {cout << my_number << endl;}

        //return a DoubleClass object that's the result of x+this
        Number& addDouble(DoubleClass& x);

        //return a DoubleClass object that's the result of x+this
        Number& addInt(IntClass& x);

        //return a DoubleClass object that's the result of x+this.
        //This should work if x is either IntClass or DoubleClass
        Number& operator+( Number& x);
};

#endif

and I've got this file (again, not written by me and can't be edited - says I can use those functions but not the '+' operator.

cpu_add.h:

#ifndef CPU_ADD_H
#define CPU_ADD_H

double add_double_double(double a, double b) {return (a+b);}
double add_int_double(int a, double b) {return ((double)(a)+b);}
int   add_int_int(int a, int b) {return (a+b);}

#endif

My goal is to implement the next functions (which you can find their declarations and functionality in poly_subtype.h above):

Number& IntClass::addInt(IntClass& x);
Number& IntClass::addDouble(DoubleClass& x);
Number& IntClass::operator+(Number& x);
Number& DoubleClass::addInt(IntClass& x);
Number& DoubleClass::addDouble(DoubleClass& x);
Number& DoubleClass::operator+(Number& x);

I hope it's more clear now.

For example, AddInt:

Number& IntClass::addInt(IntClass& x){
 int num = add_int_int(my_number, x.get_number());
 IntClass* a = new IntClass(num);
 IntClass &ref = *a;
 return ref;
}

解决方案

While you can do something like you wrote above, it is a bad stile. If a resource is allocated on the free-store you should return a pointer to it, not a reference. Even better, use a smart pointer of the appropriate kind: e.g. std::auto_pointer (or better std/boost::unique_ptr) if the resource is not held by the producer and std::shared_ptr if the opposite is the case. Your code example is legal, but the consumer of the returned reference does not (and cannot) know how to deal with the returned reference.

I can imagine returning a constant reference to an object in scenario like this:

class Producer {
 std::shared_ptr<SomeObject> mObject;

public:
 Producer() : mObject(new SomeObject) {}

 const SomeObject& GetObject() const {
  return *mObject;
 }

};

You could however return a reference to an object with static duration, which has certain drawbacks though - you do not have (appropriate) control over the lifetime of the object., for example:

SomeObject& GetSomeObjectSingletonReference() {
 static SomeObject sInstance;
 return sInstance;
}

Cheers,

Paul

这篇关于如何在C ++中返回引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆