什么应该返回int&当我们在c ++中没有合适的左值时?

时间:2016-10-08 17:08:36

标签: c++

今天,我的教授在他的电脑里写了这段代码:

class Page < ApplicationRecord

 acts_as_list :scope => :subject

 belongs_to :subject, { :optional => false }
 has_many :sections
 has_and_belongs_to_many :admin_users

 scope :visible, lambda { where(:visible => true) }
 scope :invisible, lambda { where(:visible => false) }
 scope :sorted, lambda { order("position ASC") }
 scope :newest_first, lambda { order("created_at DESC") }

 validates_presence_of :name
 validates_length_of :name, :maximum => 255
 validates_presence_of :permalink
 validates_length_of :permalink, :within => 3..255
 validates_uniqueness_of :permalink

end

我90%确定代码与上面完全相同。 但是当我在2015年的视觉工作室中写这篇文章时,我收到了错误。 编译器希望我返回一个int&amp;在第一个返回声明中。 你能帮帮我吗?

2 个答案:

答案 0 :(得分:2)

你可以这样做:

int global_incorrect_value = 42;

int& at(int index) 
{
    if (index < 0 || index >= maxsize)
    {
        cout<<"The index is not valid"<<endl;
        return global_incorrect_value;
    }
    return elements[index];
}

或者这个:

std::optional<int*> at(int index)
{
    if(index < 0 || index >= maxsize)
        return {};
    else
        return &elements[x];
}

或那:

int* at(int index)
{
    if(index < 0 || index >= maxsize)
        return nullptr;
    else
        return &elements[x];
}

甚至是:

int& at(int index)
{
    if(index < 0 || index >= maxsize)
        throw std::logic_error;
    else
        return elements[x];
}

或者如果你是极端的受虐狂:

int& at(int index)
{
    if(index < 0 || index >= maxsize)
        explode();
    else
        return elements[x];
}

但你不能“像你的教授那样” - 发布的代码甚至不接近合法的C ++。

答案 1 :(得分:-1)

因为我理解代码,我认为这个函数从数组中获取一个名为element的值,如果找到则返回值,所以我将在这种情况下解释我的答案 这是一个语法错误,你不返回任何返回值的函数,而不返回void函数,如果这个函数没有返回任何值,答案应该在内存中,因为你返回对该值的引用,请参阅示例

#include <iostream>
using namespace std;
int elements[10];
int maxsize = 10;
int notFound = -1; // this a value to know that we are access a value out of range so when return -1 we handle it and we write it as a varible not return -1 to have a refrence in memory to return 
int& at(int index) {
    if (index < 0 || index >= maxsize){
        cout<<"The index is not valid"<<endl;
        return notFound; 
    }
    return elements[index];
}

希望这有用,你的问题不明确