Question

I'm trying to define 2 classes, declare a friend function in one of them and implement it in the other. I am actually trying to get exactly what found in this post working:

How can friend function be declared for only one particular function and class?

I read the answer and thought it made sense. then implemented it in my code and it gave me the errors:

Edited:

Error 1 error LNK2019: unresolved external symbol _main referenced in function ___tmainCRTStartup ...\MSVCRTD.lib(crtexe.obj) - (solved by adding main function)

Error 2 error LNK1120: 1 unresolved externals ...\Debug\Project.exe 1 1.. - (solved by adding main function)

Error 3 IntelliSense: member "one::data1" (declared at line 19) is inaccessible ...\Friends.cpp - (Exists even after cleaning and rebuilding project)

I thought it might be a problem with how I implemented it, so I did a copy-paste to the code in the answer:

class one;

class two
{
 private:
    int data2;
 public:
    two()
    {
       data2 = 200;
    }
    // this goes fine, because the function is not yet defined. 
    int accessboth(one a);
};

class one
{
private:
    int data1;
public:
    one()
    {
       data1 = 100;
    }
    friend int two::accessboth(one a);
};

// don't forget "inline" if the definition is in a header. 
inline int two::accessboth(one a)
{
    return (a.data1 + (*this).data2);
}

but I got the same error in the same place: a.data1 was inaccessible

I then searched and found more examples that suggest the same technique to solve the problem, but they all gave me the same inaccessible error in the same place...

Is there something I'm missing? should the provided example (suggested solution from previous post) work? Something changed in the specification maybe?

thank you for any help. D

P.S I tried commenting on the previous post in order not to open a new question about this, but was unable to comment due to low reputation (I'm new here).

Was it helpful?

Solution

You are missing main function. Like this one for example:

int main() {
  one a;
  two b;
  b.accessboth(a);
}

Put it on the bottom of your file and it should compile.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top