从访问主类的保护成员 [英] Accessing protected members of class from main

查看:116
本文介绍了从访问主类的保护成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

World.cpp:

World.cpp:

World::World() {
    //something
}
World::~World() {
    //something
}
void World::doSomething(Organism *organisms[20][20]) {
    cout << organisms[1][1]->Key(); // example of what I need to do here
}
int main() {
    World *world = new World();
    World::doSomething(world->organisms);
    return 0;
}

world.h

world.h

class World {
public:
    static void doSomething(Organism *organisms[20][20]);
    World();
    ~World();
    Organism *organisms[20][20];
};

Organism.cpp

Organism.cpp

Organism::Organism(){
}
Organism::~Organism(){
}
char Organism::Key(){
    return this->key;
}

Organism.h

Organism.h

class Organism {
public:
    Organism();
    ~Organism();
    // ...
    char Key();
protected:
    char key;
    // ...
};

我需要像一台机器,创造的动物。上面的code作品非常​​好,让你知道:数组生物是指针类型的生物有机体特定的阵列,每一个有机体包含它的字符键值。
我的问题是我需要的生物有机体*保护阵列或私人的,而不是公众。还有开始的问题。

I need to make something like a machine, creating animals. The code above works very good, to let you know: the array organisms is an array of pointers to specific organisms of type Organism, every organism contains it's char key value. My problem is that I need to make the Organism *organisms array protected or private instead of public. And there begin problems.

我有不能访问的世界DoSomething的(下划线生物)申报文件World.cpp线保护成员的错误。

I have an error that I cannot access the protected member of declared in World in file World.cpp line with doSomething ( underlined organisms ).

我试着用朋友等,但没有一种方法奏效。任何想法如何从主访问此阵? (函数的参数是可以改变的,数组需要被保护/私营)任何简单的方法如何做到这一点?

I tried using friend etc. but none of the methods worked. Any idea how to access this array from main? (function parameters can be changed, the array need to be protected/private) Any simple method how to do this?

感谢您的帮助。

推荐答案

您确实可以使函数的类的朋友,像这样:

You can indeed make the main function a friend of a class like so:

int main(int, char**);

namespace N {
    struct C {
        friend int ::main(int, char**);

    private:
        int privateer = 42;
    };
}

int main(int, char**) {
    ::std::cout << N::C().privateer << "\n";
}

但是,为什么不只是让 DoSomething的非静态成员函数?

这篇关于从访问主类的保护成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆