【问题标题】:class template - can't find appropriate operator method类模板 - 找不到合适的运算符方法
【发布时间】:2016-01-02 16:14:40
【问题描述】:

我正在尝试使用类模板和运算符覆盖在 C++ 中实现自己的集合。

我的 MySet.h 文件中有以下代码:

#include "stdafx.h"
#pragma once
#include <iostream>
#include <string>
using namespace std;
#define DEFAULT_LEN 10

template <class T> class MySet
{
public:
    MySet(int len = DEFAULT_LEN)
    {
        elements = new T[len];
        count = 0;
    }

    ~MySet()
    {
        delete elements;
    }

    MySet<T> operator+(T &element)
    {
        cout << "Some code here!"; //deleted to simplify code, the problem is that this method is not seen in main
        return MySet<T>();
    }

    string writeSet()
    {
        string result = "";
        for (int i = 0;i < count; i++)
        {
            result += elements[i] + ", ";
        }
        return result;
    }

private:
    T* elements;
    int count;
};

这是我的主要内容:

#include "stdafx.h"
#include "MySet.h"

int main()
{
    MySet<int> a = MySet<int>(10);
    cout << a.writeSet();
    a = a + 2;
    a = a + 3;
    a = a + 4;
    cout << a.writeSet();
    return 0;
}

不幸的是,我在编译这些行时遇到了问题:

a = a + 2;

。输出是:

1>c:\path\main.cpp(11): error C2679: binary '+': no operator found which takes a right-hand operand of type 'int' (or there is no acceptable conversion)
1>  c:\path\myset.h(22): note: could be 'MySet<int> MySet<int>::operator +(T &)'
1>          with
1>          [
1>              T=int
1>          ]

这怎么可能?据我了解,MySet&lt;T&gt; operator+(T &amp;element) 应该足够了,因为 T 型。我错过了什么?

【问题讨论】:

  • 您不能将对非常量的引用绑定到右值(234)。缺少一些 const 说明符...编译后,UB 等着你(双免费)。
  • 您甚至没有将new []delete [] 匹配,而是阅读this

标签: c++ class templates generics


【解决方案1】:

必须是:

MySet<T> operator+(const T &element)

【讨论】:

  • 不应该返回当前实例的引用(即*this)吗?
  • 应该吗? operator+ 不会创建一个临时的吗?
  • 是的,它有效,谢谢! @πάνταῥεῖ,说明中没有具体说明,但我想我可以双向进行
  • @BlackMoses 你是对的。因为它 says here 它应该只适用于 operator+=()
猜你喜欢
  • 1970-01-01
  • 2021-03-02
  • 2015-03-17
  • 1970-01-01
  • 2015-01-21
  • 2023-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多