C++ 如何更新来自getter的变量

C++ 如何更新来自getter的变量,c++,methods,overriding,C++,Methods,Overriding,我需要我的front方法来支持在我的作业中做类似的事情。已经4个小时了。我似乎不明白。我尝试过重载=运算符,但似乎不起作用 vectD3.front() = '{'; vectD3.back() = '}'; 基本上,我需要代码在运行时不抛出错误 这是我的前后方法 public:T front() { if(currentSize > 0) { return array[0]; } else {

我需要我的front方法来支持在我的作业中做类似的事情。已经4个小时了。我似乎不明白。我尝试过重载=运算符,但似乎不起作用

vectD3.front() = '{';
vectD3.back() = '}';
基本上,我需要代码在运行时不抛出错误

这是我的前后方法

   public:T front()
   {
      if(currentSize > 0)
      {
         return array[0];
      }
      else
      {
         throw std::runtime_error("dynarray has no members");   
      }
   }
   public:T back()
   {
      if(currentSize > 0)
      {
         return array[currentSize-1];
      }
      else
      {
         throw std::runtime_error("dynarray has no members");
      }
   }

感谢是advance

您需要通过getter函数返回引用。然后你可以修改它。 大概是这样的:

class A
{
public:
    A(char d1): data(d1) {}

    char& getData()
    {
        return data;
    }
private:
    char data;
};

int main()
{
    A a('a');
    std::cout << a.getData();//data = a
    a.getData() = 'b'; 
    std::cout << a.getData();//data = b

    return 0;
}
A类
{
公众:
A(chard1):数据(d1){}
char&getData()
{
返回数据;
}
私人:
字符数据;
};
int main()
{
A(‘A’);

std::cout如果有帮助,这里是所有代码NVM不允许我使用的…你的方法应该返回一个引用。如果你不知道引用是什么,请参阅你的C++书中适当命名的章节。