调用标准方法时,例如 std::sort()
,我们只需要一个命名空间,可以进一步简单地通过 using namespace std;
我怎么能用用户定义的类来做到这一点,或者是不可能的。 (请不要使用预处理器宏解决方案)。我尝试使用这个:
#include <iostream>
using namespace std;
namespace std
{
class A
{
public:
static void foo()
{
std::cout << "foo";
}
};
}
int main ()
{
//foo(); does not work
A::foo(); //Only this works
}
更换 std
通过任何其他命名空间也不起作用。
最佳答案
When invoking a standard method, for example, std::sort(), we just need a namespace and can further simply by using namespace std; How can I do this with a user-defined class [...]
std::sort
是模板而不是函数,否则它与您可以自己编写的代码没有区别: namespace foo {
void bar() {}
}
using namespace foo;
int main() {
bar(); // ok
}
这适用于命名空间,但不适用于类的成员(类成员有 using
可以将基类范围中的某些内容带入派生类范围,但这是一个不同的主题,超出了问题的范围(没有双关语意) ),这不是您在这里要求的)。在您的示例中,没有理由
foo
应该是 A
的成员,因此您应该将其设为免费功能(如上所述)。假设你没有写 A
但是您仍然需要在不限定类名的情况下调用它,您可以将它包装在一个自由函数中。另请注意,不允许向命名空间
std
添加内容。 .如果你这样做,你的代码有未定义的行为。最后,请注意有充分的理由不鼓励使用
using some_namespace;
共。考虑一下: namespace foo1 {
void bar(){}
}
namespace foo2 {
void bar(){}
}
// lots of other code
using namespace foo1;
// lots of other code
int main() {
foo1::bar(); // this is bar from foo1
foo2::bar(); // this is bar from foo2
bar(); // to know which bar this is you have to
// look for any using directive, ie
// it makes your code much harder to read
}
代码编写一次,但阅读多次。输入的 6 个额外字符以更清晰的代码获得返回。也可以看看:Why is “using namespace std;” considered bad practice?
关于c++ - 在不使用类名和范围解析运算符的情况下调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69297101/