c++ - 无法通过引用传递值 C++

标签 c++ vector reference stack

我正在构建一个基于 Vector 类的堆栈和队列类。对于每一个,我都需要调用一个函数来修改该索引处的值。

对于堆栈,该函数是:

T &top()

但是,我似乎无法修改这个值,这就是我的最终目标。目前,我已经从堆栈函数中删除了&符号,因此该值可以显示,但不能修改。

当我在堆栈或队列中包含&符号时,错误是相同的。所以我认为问题是相同的,并且我相信它与语法相关

例如:

error C2440: 'return' : cannot convert from 'float' to 'float &'

这是我的 Stack.h

template <class T>
class Stack{
private:
    Vector<T> stack;
public:
    void push(const T &x) {stack.push_back(x);}
    void pop(){stack.pop_back();}
    bool empty(){return stack.empty();}
    int currentCapacity() const {return stack.currentCapacity();}
    int size(){return stack.size();}
    T &top() {return stack.back();}

};

这是我的 Vector 头文件,以及我在 Stack 中调用的函数:

#include<iostream>
using namespace std;

const int SIZEFACTOR = 4;

template <class T>
class Vector{
private:
    unsigned int size_Of_Vector; // # of Items in list
    unsigned int total_Vector_Capacity;//Total Capacity
    T * vector_array;//Items themselves
public:
    Vector();
    ~Vector();  
    void push_back(const T &e);
    void pop_back();
    void pop_front();
    bool empty();
    int size() const;
    void growVector();
    void shrinkVector();
    void shrinkToSize();
    int currentCapacity() const;
    T back();
    T front();
    //Operator
    const T & operator [] (int index){

        if((index >= size_Of_Vector) || index < 0){
            cout << "ERROR! Index not used: " << index
                 << " (max = " << size_Of_Vector << ")" << endl;
            return EXIT_FAILURE;            
        }    

        return vector_array[index]; 
    };//End Operator    
};//End Header Definition

template <class T> 
T Vector<T>::back(){
    if(size_Of_Vector == 0){
        cout << "Vector is EMPTY" << endl;
        return 0;
    }
    return vector_array[size_Of_Vector-1];//returns top
}

有人能帮我指出正确的方向吗?我试图达到的最终目标是能够调用类似的东西:(假设模板是 int)

x.top() += 5;

然后将修改后的值存储在堆栈中。

最佳答案

这是因为您在 vector backfront 方法中传回对象的拷贝,而不是引用。

void shrinkToSize();
int currentCapacity() const;
T back();      // < Copy returned from this method, should be T&
T front();     // < Same here!

将上面几行中的 T 更改为 T&,这样就可以开始了。

关于c++ - 无法通过引用传递值 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19083961/

相关文章:

c++ - 我可以通过 reinterpret_cast 将 int 的空指针转换为 long 类型吗

c++ - c语言实现密码安全的程序?

c++ - 如何以短时间格式验证输入字符串

java - 内存中的数据操作

c++ - vector 重新分配导致 malloc 错误

ruby-on-rails - ruby rails : two references with different name to the same model

c++ - 这是正确的 uint64_t 比较吗?

c++ - 来自类方法的 Cout 不执行任何操作

c# - 桌面 C# - 引用 Windows.Devices

c# - 在 "Add Reference"Visual Studio 2012 选项卡中看不到 SlimDX