首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >访问friend类中的受保护方法时出现问题

访问friend类中的受保护方法时出现问题
EN

Stack Overflow用户
提问于 2021-09-19 12:32:54
回答 1查看 38关注 0票数 0

我正在启动一个新项目,在World类中访问Organism的受保护方法时遇到了问题。我想我对Worldorganism的朋友的定义一定有误。我试着从World World中调用一些方法,但是编译器说它不可访问。该方法当然被设置为受保护的,因此只有派生类和朋友才能调用它们。

World.h

代码语言:javascript
复制
 #include <vector>
 #include <iostream>
using std::vector;  

#include <map>
using std::map;
#include "Organism.h"
#pragma once
class World
{
private:
    map<int, std::shared_ptr<Organism>> organims_map;
    vector <std::shared_ptr<Organism>> animals_vector;
    int x_size, y_size; 
    void initiate_aniamals();
public:
    World();
    World(int x, int y);
    void make_turn();

    
};

Organism.h:

代码语言:javascript
复制
#pragma once
#include "World.h"
class Organism
{
    friend class World;
private:
    int strength, vigor;
    int x_pos, y_pos;
    float level;
protected:
    int get_vigor() const;
    virtual void action() = 0 ;
    virtual void collision() = 0;
    /// <summary>
    /// compares animals by their vigor
    /// </summary>
    /// <param name="other organism"></param>
    /// <returns>which animal has higher vigor</returns>
    bool operator<(const Organism& other_organism);
}; 

然后在文件world.cpp中,我尝试定义方法make_turn():

代码语言:javascript
复制
void World::make_turn()
{
    //stable sort animals by their vigor
    std::stable_sort(begin(this->animals_vector), end(this->animals_vector),
        [](const Organism& organism_1, const Organism& organism_2)
        {
            return  organism_1.get_vigor(); //
        });

我在以下代码行中遇到错误:

代码语言:javascript
复制
 return  organism_1.get_vigor(); 

说明函数get_vigor是不可访问的。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-09-19 12:45:26

问题是,#pragma once不是在World.h的开始,而是在包含Organism.h之后。这导致了大量奇怪的错误,包括尽管是Organism的朋友,World不能使用它的私有方法。

这是正确的:

代码语言:javascript
复制
#pragma once
#include "Organism.h"

然而,这绝对不是:

代码语言:javascript
复制
#include "Organism.h"
#pragma once
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69243308

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档