【问题标题】:How to use assignment operator on proxy of index operator如何在索引运算符的代理上使用赋值运算符
【发布时间】:2021-07-12 11:54:32
【问题描述】:

在下面的代码中,我创建了一个模板类,它在主函数中初始化,我正在尝试分配char*,如下所示,但它不起作用。我认为问题出在我在 Proxy 类中定义的分配运算符函数中,但我无法弄清楚

#include <iostream>
using namespace std;

template <class T>
class Vector {
 public:
    T *p;

    Vector(int size) {
        p = new T[size];
    }

    class Proxy {
        Vector &a;
        int i;

     public:
        Proxy(Vector &a, int i) : a(a), i(i) {
        }

        void operator=(const T x) {
            a.p[i] = x;
        }
    };

    Proxy operator[](int i) {
        return Proxy(*this, i);
    }
};

int main() {
    Vector<char *> sv1(2);
    sv1[0] = "John";
    sv1[1] = "Doe";
}

我收到以下错误;

我已经尝试将赋值运算符函数中的参数设置为const,我还尝试将隐式类型转换为T,但没有任何效果

【问题讨论】:

  • “尝试设置const参数”是什么意思?
  • void operator=(const T x) const { a.p[i] = x; }
  • 不,你应该将模板参数设为const char *。
  • Vector&lt;const char *&gt; sv1(2); -- 其中指定模板参数为const char * 的部分不清楚?
  • 没有。 "literal strings" 是 const char *s。 C++ 不能以任何其他方式工作。

标签: c++ typecast-operator


【解决方案1】:

试试这个:

using namespace std;

template <class T>
class Vector {
public:
    T* p;
    int sz;

    Vector(int size) {
        p = new T[size];
        sz = size;
    }


    template<class T>
    class Proxy {
        Vector<T>& v;
        int i;
        
    public:
        Proxy(Vector<T>& vec, int index) :v(vec),i(index) { }

        void operator= (const T val) { v.p[i] = val; }
    }; 

    Proxy<T> operator[](int index) { return Proxy<T>(*this, index); }
};

您的代码将适用于任何基本类型(int、char、double)和指针,但例如,不能使用以下代码:

int main() {
    Vector<char*> sv1(2);
    sv1[0] = "John";
    sv1[1] = "Doe";
}

首先,Vector 指向char*,而不是字符串文字 (const char*)。您必须使用 C 风格的演员表或 const_cast 来转换它。示例:

int main() {
    Vector<char*> sv1(2);
    sv1[0] = const_cast<char*>("John"); //succeeds
    sv1[1] = (char*)"Doe"; //succeeds

    sv1[0] = "John"; //fails
    sv1[1] = "Doe"; //fails
}

在 C++ 中,字符串文字始终是 const char*。

【讨论】:

    【解决方案2】:

    你会遇到同样的错误写代码:

    char *whatever = "某事";

    这段代码至少对于字符串是绝对错误的:

    void operator=(const T x)
    {
        a.p[i] = x;
    }
    

    第一步:分配缓冲区; 第 2 步:将字符串复制到分配的缓冲区。

    您的代码适用于 char、int 等原语。以下代码应该可以工作:

    int main() {
        Vector<char> sv1(2);
        sv1[0] = 'J';
        sv1[1] = 'D';
    }
    

    【讨论】:

      猜你喜欢
      • 2011-12-12
      • 2011-11-16
      • 1970-01-01
      • 1970-01-01
      • 2018-12-18
      • 2013-11-30
      • 2015-10-02
      • 1970-01-01
      • 2013-06-28
      相关资源
      最近更新 更多