首页 \ 问答 \ c ++ - java风格的静态常量初始化(c++ - java style static constant initialization)

c ++ - java风格的静态常量初始化(c++ - java style static constant initialization)

我是c ++的新手。 我试图在c ++中创建一个静态常量容器。 在java中,我们通常通过静态常量初始化来实现。 例如

class ConstantDefinition {
  public static const List<String> stringList = new ArrayList<String>();
  static {
       stringList.add("foo");
       stringList.add("boo");
       ...blah
       }                       
} 

java的工作方式,我不需要调用特定的方法来完成初始化。 一旦将类加载到JVM中,静态块就会被初始化。 但是在c ++中,我们没有与java相同的类加载机制。 我想要的是拥有一个不可修改的容器的副本,我可以使用它而不必每次都创建类对象。 我理解的一种方法是创建一个类(类似于我上面的java示例)并定义一个const静态容器。 但我发现在C ++中编写这种代码很困难,因为我不能在不调用方法的情况下进行初始化。 那么实现这一目标的最佳方法是什么? 第二种方法可能是我定义头文件并在命名空间内初始化全局变量。 如果我采用这种方法,那么每当我包含该头文件或者将使用相同的头文件时,它会创建不同的全局变量吗?

谢谢,RG


I am a newbie in c++. I am trying to create a static constant container in c++. In java we typically do that by static constant initialization. For e.g.

class ConstantDefinition {
  public static const List<String> stringList = new ArrayList<String>();
  static {
       stringList.add("foo");
       stringList.add("boo");
       ...blah
       }                       
} 

The way java works, I don't need to call a specific method to get the initialization done. Static block gets initialized once the class is loaded into JVM. But in c++ we don't have the same class loading mechanism as java. And what I want is to have a single copy of non modifiable container that I can use without creating the class objects every time. One way I understand is that I create a class(similar to my java example above) and define a const static container. But I am finding it difficult to write that kind of code in C++ because I can't do the initialization without calling a method. So what's the best way to achieve this? The second approach could be that I define a header file and initialize global variables within namespaces. If I take this approach then would it create different global variable each time when I include that header file or the same one will be used?

Thanks, RG


原文:https://stackoverflow.com/questions/23830679
更新时间:2023-07-24 15:07

最满意答案

要详细说明dkackman的答案,理想情况下,您的工厂将返回子类型的对象,但声明为父类型。

class Factory
{
    public Parent Foo()
    {
        return new Child();
    }

    public Parent Bar()
    {
        return new OtherChild();
    }
}

基本的想法是你的调用代码不应该关心它返回哪个子类。 这是Liskov替代原则的一个概念。


To elaborate on dkackman's answer, your factory ideally would return objects of child types, but declared as the parent type.

class Factory
{
    public Parent Foo()
    {
        return new Child();
    }

    public Parent Bar()
    {
        return new OtherChild();
    }
}

The basic idea is that your calling code shouldn't care which child class it gets back. This is one concept of the Liskov Substitution Principle.

相关问答

更多
  • 这非常适合模板方法模式 。 将字符串分解为单独的方法: class FooBase(object): @property def bleh(self): raise NotImplementedError() # consider making this an abstract base class with the abc module def almost_common_method(self, params, force): pa ...
  • 以下是三种流行的JavaScript模式。 由于关闭,这些事情容易实现: 模块模式 - Eric Miraglia的示例(并且流行) 记忆 - 例如Oliver Steele Currying - Dustin Diaz的例子 您可能还想查看: 专业JavaScript设计模式由Ross Harmes和Dustin Diaz 以下是Diaz 2008年提出的Google I / O谈话,他在他的书中讨论了一些话题: Google I / O 2008 - 表达式语言中的设计模式 The following ...
  • 您对OOP中各种功能的类比肯定是有效的。 在谈论集合/容器/ Hashmaps时,泛型绝对是最有意义的。 不过,它们确实在其他地方有用。 例如,如果银行想要以多种货币处理票据,他们可以编写公共类moneyProcessor 但是, 不需要泛型。 在Flight界面的上下文中,没有太多理由使用泛型。 这让我想到另一点: 仅仅因为别人以某种方式做某事并不意味着你必须这样做。 OOP非常灵活有一个原因。 总有不止一种正确的方法。 如果方法将Object作为参数,那么它不是世界末日。 请确保您以后可以阅读。 :) ...
  • 你给出的方法的问题是你没有遵循任何形式的“权力分立”原则。 您的Display对象中包含一个数据库,以及如何连接它的逻辑; 这可能不是最好的方法(“上帝的对象”)。 遵循MVC(模型 - 视图 - 控制器)原则可能是一个更好的主意,其中您有一个类知道您的模型(数据库),另一个知道如何将模型转换为将呈现的对象(控制器) ,第三个实际显示数据的所有CSS优点(视图,通常只是一个PHP模板文件)。 我建议你看看现有的MVC框架 - 我使用的是QCubed( http://qcu.be ),还有其他的 - Symf ...
  • 流动性示例: 假设以下类: 动物 犬 狗 正如您所料, Canine延伸Animal和Dog延伸Canine 。 设计不好Animal一种方法是给它一个方法talk()打印出bark 。 也许,这个应用程序的初衷只针对狗,因此talk方法吠叫很好。 但是在另一个代码库中重用它会导致问题。 假设我们想扩展Animal并创建Bird 。 鸟不吠:) 很难想象有人会这样做。 但它始终在发生。 基类没有被抽象出来,这导致错误的代码使得难以纠正/重用。 有人可能会说Bird类可以覆盖talk方法。 然而,这会起作用, ...
  • 它看起来像Map 。 It looks like a job for a Map.
  • 要详细说明dkackman的答案,理想情况下,您的工厂将返回子类型的对象,但声明为父类型。 class Factory { public Parent Foo() { return new Child(); } public Parent Bar() { return new OtherChild(); } } 基本的想法是你的调用代码不应该关心它返回哪个子类。 这是Liskov替代原则的一个概念。 To elaborate ...
  • 介绍一个新的界面。 public interface IMeasurable { someReturnType GetMeasure(); } public class Circle : IMeasurable { //some other methods public someReturnType GetMeasure() { return GetArea(); } } public class Cube : IMeasurable { //some other me ...
  • 我能给你的最多OOP建议是为每一项/一条信息创建一个类。 例如: public abstract class ContactInfo { /* ... */ } public class Address extends ContactInfo { /* ... */ } public class PhoneNumber extends ContactInfo { /* ... */ } public class EmailAddress extends ContactInfo { /* ... */ ...
  • 您使用的设计不是想法(恕我直言)。 首先,将non-circular重命名为Polygon (另外,对于第一个字母,我们使用大写)。 根据实现, Circle是一个特定的Ellipse所以我在这里使用了继承 Shape < -- Circular < -- Ellipse < -- Circle < -- Polygon < -- Triangle < -- Equilateral < -- ... //don ...

相关文章

更多

最新问答

更多
  • h2元素推动其他h2和div。(h2 element pushing other h2 and div down. two divs, two headers, and they're wrapped within a parent div)
  • 创建一个功能(Create a function)
  • 我投了份简历,是电脑编程方面的学徒,面试时说要培训三个月,前面
  • PDO语句不显示获取的结果(PDOstatement not displaying fetched results)
  • Qt冻结循环的原因?(Qt freezing cause of the loop?)
  • TableView重复youtube-api结果(TableView Repeating youtube-api result)
  • 如何使用自由职业者帐户登录我的php网站?(How can I login into my php website using freelancer account? [closed])
  • SQL Server 2014版本支持的最大数据库数(Maximum number of databases supported by SQL Server 2014 editions)
  • 我如何获得DynamicJasper 3.1.2(或更高版本)的Maven仓库?(How do I get the maven repository for DynamicJasper 3.1.2 (or higher)?)
  • 以编程方式创建UITableView(Creating a UITableView Programmatically)
  • 如何打破按钮上的生命周期循环(How to break do-while loop on button)
  • C#使用EF访问MVC上的部分类的自定义属性(C# access custom attributes of a partial class on MVC with EF)
  • 如何获得facebook app的publish_stream权限?(How to get publish_stream permissions for facebook app?)
  • 如何防止调用冗余函数的postgres视图(how to prevent postgres views calling redundant functions)
  • Sql Server在欧洲获取当前日期时间(Sql Server get current date time in Europe)
  • 设置kotlin扩展名(Setting a kotlin extension)
  • 如何并排放置两个元件?(How to position two elements side by side?)
  • 如何在vim中启用python3?(How to enable python3 in vim?)
  • 在MySQL和/或多列中使用多个表用于Rails应用程序(Using multiple tables in MySQL and/or multiple columns for a Rails application)
  • 如何隐藏谷歌地图上的登录按钮?(How to hide the Sign in button from Google maps?)
  • Mysql左连接旋转90°表(Mysql Left join rotate 90° table)
  • dedecms如何安装?
  • 在哪儿学计算机最好?
  • 学php哪个的书 最好,本人菜鸟
  • 触摸时不要突出显示表格视图行(Do not highlight table view row when touched)
  • 如何覆盖错误堆栈getter(How to override Error stack getter)
  • 带有ImageMagick和许多图像的GIF动画(GIF animation with ImageMagick and many images)
  • USSD INTERFACE - > java web应用程序通信(USSD INTERFACE -> java web app communication)
  • 电脑高中毕业学习去哪里培训
  • 正则表达式验证SMTP响应(Regex to validate SMTP Responses)