Click here to Skip to main content
15,886,873 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello
I wrote a program where friend functions give errors when defined outside the program.
that said " "n" , "A" was not declared in this scope"
and when this is " complex l; l.A[j] " , said: no match for 'operator<' (operand types are "vector" and "vector""
can you help me?

What I have tried:

class vector{
 private:
	  vector *A;
	  int a;
	  int n;
	  public:
	  vector (int);
	  vector(){};
	  void output();
	  friend vector min();
	  friend int search(int s);
<pre>vector min()
{
	vector l;
	vector m;
	vector temp;
	for (int i=0;i<l.n;i++)
	m=l.A[0];
	for (int j=1;j<l.n;j++)
	{
	if (l.A[j]<m)
	{
		temp=l.A[j];
		l.A[j] =m;
		m=temp;
	}
    };
    }
Posted
Updated 15-Jun-23 12:18pm
v2
Comments
Richard MacCutchan 15-Jun-23 15:08pm    
Where is the other code and where does the error occur?

A friend function needs to know which instance of the class to operate on. Consider
C++
class C {
  private:
     int x;
  public:
  A(int n) : x(n) {};

  friend void fn(void);
}

void fn()
{
    std::cout << x << '\n';  // Don't know which C instance to use!
}

int main()
{
   C x(1);
   C y(2);
   fn();  // <- which C object does this call to fn() access?
}
A few simple changes correct this:
C++>
class C {
private:
    int x;
public:
    C(int n) : x(n) {}
    friend void fn(const C&);
};

void fn(const C& c) {
    std::cout << c.x << '\n';  // Because we're a friend, we can access c.x!
}

int main()
{
    C x(1);
    C y(2);

    fn(x);
    fn(y);
}
 
Share this answer
 
Comments
CPallini 16-Jun-23 7:23am    
5.
We can't guess with the fragment of code posted. This tutorial section on friend functions might help : cplusplus.com tutorial friendship & inheritance/[^]

ETA : actually it is fairly clear what some of the problems are. Here is the code for the function with indentation added :
C++
vector min()
{
    vector l;
    vector m;
    vector temp;
    for (int i=0;i<l.n;i++)
        m=l.A[0];

    for (int j=1;j<l.n;j++)
    {
        if (l.A[j]<m)
        {
            temp=l.A[j];
            l.A[j] =m;
            m=temp;
        }
    }   // ;  the semicolon here is unnecessary
}
There are several things wrong with this.
- All references to m are bad because it is a vector.
- The vector l is accessed several times but it is never initialized.
- The variable temp is declared as a vector but it should be of the type contained by the vector and that is not clear.
- The function should return a vector but it does not.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900