隐藏'静态'类变量

dec*_*iar 2 c++ static-members static-functions

所以我最近发现了一些使用特定技术的源代码(成语?)我以前没见过; 简而言之; 它不是使用相关类的静态变量,而是在类源文件中使用局部变量.

myclass.h

class myclass {
    //static int myint;

public:
    myclass();
    ~myclass();
    int count();
};
Run Code Online (Sandbox Code Playgroud)

myclass.cpp

#include "myclass.h"

int myint = 0;

myclass::myclass() {
    myint++;
}
myclass::~myclass() {
    myint--;
}

int myclass::count() {
    return myint;
}
Run Code Online (Sandbox Code Playgroud)

main.cpp中

#include "myclass.h"
#include <iostream>

int main() {
    myclass aclass;
    myclass theclass;

    std::cout << theclass.count(); //outputs 2
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我的问题是,为什么有人会采用这种方法而不是使用静态变量?

我对它的看法是,理想情况下,变量只能为myclass类(私有静态)所知,并且继承根本不重要(在这种情况下),这可能会阻止其他人知道这个变量.但这是我能看到的唯一优势; 不确定这是否值得保证.

同样的问题适用于私有的(静态/非静态)成员函数; 当继承不重要时.

编辑:读完之后,我要做的是因为有些人仍然使用C编程风格...

Jam*_*lis 7

使用静态成员变量或全局变量或本地声明的静态变量并不重要; 唯一重要的是对象必须具有静态存储持续时间.除此之外,选择主要基于个人偏好或编码风格指南.

不幸的是,这段代码基本上是错的.虽然myint是"隐藏"并且只能从myclass.cpp中直接访问,但它仍然具有外部链接.这意味着可以从其他翻译单元访问(通过extern int myint在其他翻译单元中使用),并且其定义可能与myint其他翻译单元中的其他定义冲突.

要纠正这个问题,应该声明static它(给它内部链接),或者最好,它应该在一个未命名的命名空间中声明,

namespace {
    int myint;
}
Run Code Online (Sandbox Code Playgroud)

(未命名的命名空间中的对象可能仍然具有外部链接,但它具有唯一的名称,因此不能通过其名称从编译它的转换单元外部使用它.)

  • 对于它的价值,大多数在线C++教程要么在技术上不正确,要么提倡糟糕的风格.(很遗憾,真的......) (3认同)