为什么静态成员变量需要内联声明而静态成员函数不需要?

时间:2021-04-16 03:25:42

标签: c++ class static inline

我正在完成一本书中的练习,并编写了以下课程:

#ifndef BOX_H
#define BOX_H

#include <cstddef> // for std::size_t

class Box {

    private:
        double length {1.0},
               width  {1.0},
               height {1.0};
        
        inline static std::size_t object_count {};
    
    public:
        Box() = default;
        Box(double length, double width, double height);
        explicit Box(double side);
        Box(const Box& box);
        
        double volume() const;
        bool has_larger_volume(const Box& other) const;
        friend double surface_area(const Box& box);

        double get_length() const { return this->length; };
        double get_width()  const { return this->width;  };
        double get_height() const { return this->height; };

        void set_length(double length) { if (length > 0) this->length = length; };
        void set_width(double width)   { if (width > 0)  this->width = width;   };
        void set_height(double height) { if (height > 0) this->height = height; };

        static std::size_t get_object_count() { return Box::object_count; }

};

#endif

我的问题特别涉及在此上下文中使用 inline 关键字。我知道无论类对象是否存在,静态成员变量都会在运行时创建一次。 object_count 将被定义多次,每个翻译单元一次,因此有必要使用 inline 对其进行限定以允许这种行为。

但是,为什么不需要用内联来限定 get_object_count() 呢?为什么这不会破坏 ODR?无论是否声明为静态,所有成员函数都隐式内联吗?

0 个答案:

没有答案