我应该使用类内初始化器还是在类外部定义中初始化静态const数据成员?

时间:2019-07-10 23:38:39

标签: c++ oop static const

如果我有一个具有静态const数据成员的类,那么初始化它的最佳方法是什么:

class Circle{
    public:
        //...
    private:
        static const double PI_ = 3.14; // 1
        //static const double PI_; // 2
};

double Circle::PI_; // 1   is this redundant?
//double Circle::PI_ = 3.14;

正如您在上面第一次看到的那样,我使用类内初始化程序初始化PI_,然后在类外定义了它而没有任何初始化程序。

第二次,我只是在没有初始化程序的类中声明了它,并在类之外使用了初始化程序对其进行了定义。

  • 哪种方法最好?
  • 只要提供了类内初始化程序,在类外的PI_的定义是否多余?
  • 我可以说为const静态数据成员提供类内初始化程序是“定义”而不是“声明”吗?

  • 也在《 C ++入门》第五版中:

    *If the member is used only in contexts where the compiler can substitute the member’s value, then an initialized const or constexpr static need not be separately defined. However, if we use the member in a context in which the value cannot be substituted, then there must be a definition for that member. For example, if the only use we make of period is to define the dimension of daily_tbl, there is no need to define period outside of Account. However, if we omit the definition, it is possible that even seemingly trivial changes to the program might cause the program to fail to compile because of the missing definition. For example, if we pass Account::period to a function that takes a const int&, then period must be defined.*

但是我尝试了一下,却在课外没有定义地工作了?!!!

谢谢!

1 个答案:

答案 0 :(得分:0)

您最好只使用constexpr,这意味着您可以将其全部保留在类定义之内

    static List<Book> books = new ArrayList<>();
    static List<Person> people = new ArrayList<>();

    public void buyBook(Book bookWritten, Person buyerName) {
        System.out.println("Write your name: ");

        String bookWanted = scanner.nextLine();

        System.out.println("Write the book you want: ");    

        String customerName = scanner.nextLine();

        for(int b = 0; b<books.size(); b++) {
            if(books.get(b).equals(bookWritten)) {
                bookWritten.setBuyer(buyerName);
            }
        }       
        for(int b = 0; b<people.size(); b++) {
            if(people.get(b).equals(buyerName)) {
                buyerName.addBooksBought(bookWritten);
            }
        }
    }