首页 > 解决方案 > comparing objects of class in a vector using operator overloading

问题描述

so I have a class A - parent and B - child, i also have a class c thats unrelated that holds a vector of child objects. Im trying to sort the vector using a compare function in class A that uses operator overloading and having diffcultly making this comparison this is the a.hpp and a.cpp combined

class c; //forward declare
class a{
a();

setfunc(string name){names=name}; //added names to vector
getFunc(){return names};
 
//use in other class  
friend bool compare(const a& A,const a& A1) //would like to compare vector element object
if(A.name == A1.name)
{
 return false;
}
if(A.name > A1.name)
{return true;}
if(A.name < Al.name)
{return false;}
else
return false;
}


friend bool operator==(const a& A,const a& A1)
{return A.names == A1.names};
friend bool operator<(const a& A,const a& A1)
{return A.names < A1.names};
friend bool operator>(const a& A,const a& A1) //im using the operators bcuz my understanding it is good practice to use with compare function

//and its a way to compare objects

{return A.names > A1.names};

friend class c;
private:
 string names;
}

theres another class b which inherited all the variables thats all done done correct, then class c holds the vector

#include "a.hpp"
class c
class c{
c();

setVec(const a& A)
{
 A.getFunc(); //pushing objects into vector
vec.push_back(A);
}

Vecsort(const a& A,const a& A1) //not sort algo
{
 for(int i = 0; i < vec.size();i++)
{
 if(compare(A,A1) == true) // how would i sent this vec[i] and vec[i+1] through there
{
 swap(A,A1)                // to be received by the compare func
 i = 0 ;                    //because currently the only thing it compares is the last 
                           //object that was set
}

private:
vector<b> vec; //child of a objects
}

TLDR, have 3 class, a - parent , b - child . c - friend. Ive initialized all parent objects through the child class in main using set func's and sent it to the friend class to sort in a vector, how do i successfully sent a vector element object to that compare() function to be compared? do i need a [] operator or do i need to change the params in the compare() to take a const vector<b&> object?

标签: c++classoopoperator-overloadingfriend

解决方案


推荐阅读