1

I have a class Table which has a member function std::vector<Attribute> attributeVec(); where Attribute is a seperate class.

I am working with code that would like to do something of the form

if (tableA.attributeVec() == tableB.attributeVec()){ ...

Where tableA and tableB are Table objects. I'm getting a lot of weird compiler errors in Visual Studio 2012 that say things like

binary '==' : no operator found which takes a left-hand operand of type 'const DatabaseAPI::Attribute' (or there is no acceptable conversion)

So I believe the vectors cannot be compared like that. It would make my life easier if I could get this code to compile, but how could I do that? Can I define the operator? Do I need to rewrite some of the Attribute class so they can be compared?

Specifics: After writing an API, I was given a set of tests which, if reasonable, need to work. While I believe this at least makes unreasonable assumptions about my code (given my API), it wouldn't hurt to implement this in my code.

Thanks!

4

4 回答 4

2

You need operator== implemented in your Attribute class:

class Attribute {
  bool operator== (const Attribute& other) const {
   // return true if *this == other, otherwise return false
  }
}

BTW: As juanchopanza noticed, it is possible that you could return just a reference to the vector from your attributeVec() function, instead of a copy of it:

std::vector<Attribute>& attributeVec();

That would be more efficient and the comparison (using the operator==) in an expression:

o1.attributeVec() == o2.attributeVec()

still work OK.

于 2013-02-19T22:47:58.933 回答
2

Vectors can be compared using ==, but their contained type (Attribute in this case) must have a comparison operator==. If you give that to the Attribute class, the comparison should work.

On an unrelated note, that his method

std::vector<Attribute> attributeVec();

is returning a copy of a vector. You have to think whether this is the behaviour you really want.

于 2013-02-19T22:48:04.763 回答
1

The error is basically self explanatory, you need operator== on Attribute.

于 2013-02-19T22:49:03.913 回答
1

看看std::equal;第二种形式允许您指定自己的比较函数。

例子:

bool compareAttributes (const Attribute &a, const Attribute &b) { /* ... */ }

// assumes attributeVec() returns a reference; if not, then remove '&'
const std::vector<Attribute>& attribsA = tableA.attributeVec();
const std::vector<Attribute>& attribsB = tableB.attributeVec();

if(attribsA.size()==attribsB.size() &&
    std::equal(attribsA.begin(), attribsA.end(),
    attribsB.begin(), compareAttributes))
{ /* ... */ }

理想情况下,attributeVec()返回对属性向量的引用。如果你不能这样写,那么attribsAandattribsB不应该被定义为引用。(在这种情况下,您可能会考虑编写一个Table不需要生成向量的比较函数Attribute。)

于 2013-02-19T23:11:11.913 回答