草庐IT

c++ - 是否可以在每个类中只传递一次变量而不是将其设为静态?

coder 2024-02-14 原文

这个问题(松散地)与我昨天问的问题有关 here .

我刚刚重构了一个容器类 ( Ecosystem ),其中包含指向 Individual 的指针小号:

class Ecosystem
{
    // This is an interface class providing access
    // to functions in Individual without exposing
    // the Individual class.
    // It performs global operations on the entire ecosystem
    // (like sorting individuals based on certain criteria)
    // but is also capable of invoking functions from the
    // Individual class.
    // It also holds the global configuration for this ecosystem.
    private:
        Config config;
        std::map<int, std::shared_ptr<Individual> > individuals;
    public:
        Ecosystem() {};
        void sort_individuals();
        void func1(int _individual_id)
        {
            individuals[_individual_id]->func1(config);
        }

        void func2(int _individual_id)
        {
            individuals[_individual_id]->func2(config);
        }
        // etc...
};

class Individual
{
    private:

    public:
        Individual() {};
        void func1(const Config& _config)
        {
            // Operations using _config.param_1, _config.param_2, ... 
        }

        void func2(const Config& _config)
        {
            // Operations using _config.param_n, _config.param_m, ... 
        }
        // etc...
}

我现在处于必须通过config的情况几乎所有对 Individual 的函数调用对象。最初我想,好吧,我就做一个 static Config config;里面Individual ,但很快我意识到我需要能够创建多个具有不同配置的共存生态系统。

如果我理解 static 的含义正确,如果我有 static Config config;里面Individual其赋值为 config来自 Ecosystem ,每次我创建一个新的生态系统时,它都会被覆盖。

我的问题是:有没有办法通过 config 一次到 Individual 类而不使其成为静态以避免将其作为每个函数的参数传递?

我考虑过 Config* config在两个EcosystemIndividual ,但这意味着每个人都会有一个指向配置对象的指针,这看起来很笨重。我需要的是一个静态成员的等价物,如果它有意义的话,其范围是容器层次结构。

一旦创建,Config 对象将不会被更改,因此可能有一个 const Config config; .

提前感谢您的任何建议!


编辑 1

谢谢大家的回复。 Matthew Kraus 指出我在最初的问题中没有提供我的生态系统类的正确构造函数,这当然是我的疏忽。我现在明白它可能是相关的,但我更多地关注于说明我所追求的变量访问类型而不是我的类是什么样的,所以我提供了一个简单的例子。如果我的额外评论给讨论带来了困惑,我深表歉意!

这里提出的解决方案都很好,但是我从答案中可以看出,C++没有任何方法可以定义此类类级变量而不将它们定义为static。 .我需要的是一个类级变量,其范围仅限于其容器。这只是我的想法的一个例子,它不会编译(我现在可以肯定这不能在 C++ 中完成):

class Ecosystem
{
    // This is an interface class providing access
    // to functions in Individual without exposing
    // the Individual class.
    // It performs global operations on the entire ecosystem
    // (like sorting individuals based on certain criteria)
    // but is also capable of invoking functions from the
    // Individual class.
    // It also holds the global configuration for this ecosystem.

    private:

        Config config;
        std::map<int, std::shared_ptr<Individual> > individuals;

    public:
        Ecosystem(const std::string& _file_name)
        {
            Config cfg(_file_name);

            config = cfg;

            // This is done before any Individual objects are created.
            Individual::set_config(cfg);

            for (int i = 1; i <= 10; ++i)
            {
                individuals[i] = std::make_shared<Individual>();
            }
        };

        void sort_individuals();

        void func1(int _individual_id)
        {
            individuals[_individual_id]->func1();
        }

        void func2(int _individual_id)
        {
            individuals[_individual_id]->func2();
        }
        // etc...
};

class Individual
{
    private:
        // v--- No such thing!
        scoped static Config config;

    public:
        Individual() {};

        void func1()
        {
            // Operations using config.param_1, config.param_2, ... 
        }

        void func2()
        {
            // Operations using config.param_n, config.param_m, ...
        }

        // v--- No such thing!
        scoped static void set_config(const Config& _config)
        {
            config = _config;
        }
        // etc...
}

int main(int argc, char* argv[])
{
    Ecosystem ecosystem1("config_file1.txt");

    Ecosystem ecosystem2("config_file2.txt");

    // Conduct experiments with the two ecosytems.
    // Note that when ecosystem2 is created, the line
    //
    // Individual::set_config(cfg);
    //
    // should *not* overwrite the class-level variable
    // config set when ecosystem1 was created. 
    // Instead, it should create a
    // class-level variable but limited to the scope of ecosystem 2.

    // This operates on Individual 1 in ecosystem 1
    // with the parameters set in config_file1.txt
    ecosystem1->func1(1);

    // This operates on Individual 1 in ecosystem 2
    // with the parameters set in config_file2.txt
    ecosystem2->func1(1);

    return 0;
}

我会同意在构建时将指向配置的指针传递给每个人的建议。这会浪费空间,但应该是最容易维护的解决方案。

再次感谢大家的意见,如果问题令人困惑,我们深表歉意。

最佳答案

如果我没理解错的话,将配置传递给 Individual 的构造函数应该这样做:

class Individual {
    const Config& config_;
public:
    Individual(const Config& c) : config_(c) {}
    void func1() {
        // use config_
    }
};

您仍然必须将 Config 传递给每个单独的构造函数,但这是一个点,而不是 Individual 将具有的许多函数。另外,如果觉得创建一个Individual太麻烦,可以将其封装成一个工厂方法。

关于c++ - 是否可以在每个类中只传递一次变量而不是将其设为静态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32002421/

有关c++ - 是否可以在每个类中只传递一次变量而不是将其设为静态?的更多相关文章

  1. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  2. ruby-on-rails - 如何验证 update_all 是否实际在 Rails 中更新 - 2

    给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru

  3. ruby - 使用 Vim Rails,您可以创建一个新的迁移文件并一次性打开它吗? - 2

    使用带有Rails插件的vim,您可以创建一个迁移文件,然后一次性打开该文件吗?textmate也可以这样吗? 最佳答案 你可以使用rails.vim然后做类似的事情::Rgeneratemigratonadd_foo_to_bar插件将打开迁移生成的文件,这正是您想要的。我不能代表textmate。 关于ruby-使用VimRails,您可以创建一个新的迁移文件并一次性打开它吗?,我们在StackOverflow上找到一个类似的问题: https://sta

  4. ruby - 我可以使用 Ruby 从 CSV 中删除列吗? - 2

    查看Ruby的CSV库的文档,我非常确定这是可能且简单的。我只需要使用Ruby删除CSV文件的前三列,但我没有成功运行它。 最佳答案 csv_table=CSV.read(file_path_in,:headers=>true)csv_table.delete("header_name")csv_table.to_csv#=>ThenewCSVinstringformat检查CSV::Table文档:http://ruby-doc.org/stdlib-1.9.2/libdoc/csv/rdoc/CSV/Table.html

  5. ruby-on-rails - 如何优雅地重启 thin + nginx? - 2

    我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server

  6. ruby - 检查数组是否在增加 - 2

    这个问题在这里已经有了答案:Checktoseeifanarrayisalreadysorted?(8个答案)关闭9年前。我只是想知道是否有办法检查数组是否在增加?这是我的解决方案,但我正在寻找更漂亮的方法:n=-1@arr.flatten.each{|e|returnfalseife

  7. ruby - 我可以使用 aws-sdk-ruby 在 AWS S3 上使用事务性文件删除/上传吗? - 2

    我发现ActiveRecord::Base.transaction在复杂方法中非常有效。我想知道是否可以在如下事务中从AWSS3上传/删除文件:S3Object.transactiondo#writeintofiles#raiseanexceptionend引发异常后,每个操作都应在S3上回滚。S3Object这可能吗?? 最佳答案 虽然S3API具有批量删除功能,但它不支持事务,因为每个删除操作都可以独立于其他操作成功/失败。该API不提供任何批量上传功能(通过PUT或POST),因此每个上传操作都是通过一个独立的API调用完成的

  8. ruby - 检查字符串是否包含散列中的任何键并返回它包含的键的值 - 2

    我有一个包含多个键的散列和一个字符串,该字符串不包含散列中的任何键或包含一个键。h={"k1"=>"v1","k2"=>"v2","k3"=>"v3"}s="thisisanexamplestringthatmightoccurwithakeysomewhereinthestringk1(withspecialcharacterslike(^&*$#@!^&&*))"检查s是否包含h中的任何键的最佳方法是什么,如果包含,则返回它包含的键的值?例如,对于上面的h和s的例子,输出应该是v1。编辑:只有字符串是用户定义的。哈希将始终相同。 最佳答案

  9. ruby-on-rails - Ruby 检查日期时间是否为 iso8601 并保存 - 2

    我需要检查DateTime是否采用有效的ISO8601格式。喜欢:#iso8601?我检查了ruby​​是否有特定方法,但没有找到。目前我正在使用date.iso8601==date来检查这个。有什么好的方法吗?编辑解释我的环境,并改变问题的范围。因此,我的项目将使用jsapiFullCalendar,这就是我需要iso8601字符串格式的原因。我想知道更好或正确的方法是什么,以正确的格式将日期保存在数据库中,或者让ActiveRecord完成它们的工作并在我需要时间信息时对其进行操作。 最佳答案 我不太明白你的问题。我假设您想检查

  10. ruby - 检查日期是否在过去 7 天内 - 2

    我的日期格式如下:"%d-%m-%Y"(例如,今天的日期为07-09-2015),我想看看是不是在过去的七天内。谁能推荐一种方法? 最佳答案 你可以这样做:require"date"Date.today-7 关于ruby-检查日期是否在过去7天内,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/32438063/

随机推荐