命名空间内的类和该类问题的全局获取和设置

问题描述 投票:0回答:1

我无法访问在类命名空间::类中声明的私有成员

你知道如何实现我在网上搜索但找不到任何解决我问题的方法吗?

#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);
}
c++ class namespaces friend
1个回答
1
投票

您需要转发声明

getCijena
,并且因为它需要引用
Osoba
,所以您还需要转发声明该类之前:

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

在线查看:https://godbolt.org/z/b7Kx1deh7

© www.soinside.com 2019 - 2024. All rights reserved.