Search code examples
c++classnamespacesfriend

class inside namespace and global get and set of that class issue


i cannot access private member of declared in class namespace::class

Do you have any idea how to achieve that i was searching on the web and can't find anything that solves my problem.

#include <iostream>
#include <algorithm>
#include <vector>
#include <functional>
#include <string>
#include <ctime>
#include <iomanip>
#include <memory.h>
#define cahr char //anti-disleksija
#define enld endl //anti-disleksija
using namespace std;

// int getCijena(Osoba& a); ---> tryed prototype
namespace Punoljetna_osoba {
    class Osoba {
        int starost;
    public:
        string ime, Prezime;
        friend int ::getCijena(Osoba& a);
        void setStarost(int a);
    };
}
using namespace Punoljetna_osoba;

int getCijena(Osoba& a) {
    return a.starost;
}

void Osoba::setStarost(int a) {
    if (18 <= a && 100 >= a)
        starost = a;
    else cout << "niste punoljetni ili ste vec umrli";
}



int main() {
    Osoba a;
    a.setStarost(50);
    //cout << getCijena(a);
}

Solution

  • You need to forward declare getCijena, and because it requires a reference to Osoba, you need to also forward declare that class before:

    namespace Punoljetna_osoba {
        class Osoba; // forward declare Osoba class
    }
    
    // forward declare function
    // note that it needs to refer to full name of the class since it's in different namespace
    int getCijena(Punoljetna_osoba::Osoba& a); 
    
    namespace Punoljetna_osoba {
        class Osoba {
            int starost;
        public:
            string ime, Prezime;
            friend int ::getCijena(Osoba& a);
            void setStarost(int a);
        };
    }
    
    // rest of the code
    

    See it online: https://godbolt.org/z/b7Kx1deh7