gpt4 book ai didi

c++ - 关于命名空间、类和作用域

转载 作者:行者123 更新时间:2023-11-30 00:37:11 24 4
gpt4 key购买 nike

我有一个类 NormalCalculator。在 NormalCalculator 中,我定义了一个 struct GLpoint

随着项目的进展,我在代码的其他地方发现了 GLpoint 的用途,但我发现必须编写 NormalCalculator::GLpoint 不整洁且会污染屏幕> 每次我希望在我的解决方案中的其他地方使用 GLpoint 结构时,在 NormalCalculator 类之外。

有什么办法可以让编译器知道 NormalCalculator.h 中存在 GLpoint,并让我将它称为 GLpoint ?我很确定应该有办法。

我试过了

using NormalCalculator

using NormalCalculator::GLpoint  

如预期的那样,这些不起作用,因为 NormalCalculator 是一个类而不是命名空间。

最佳答案

您可以使用 typedef。

namespace my_ns {
typedef NormalCalculator::GLpoint GLpoint;
}

虽然我真的建议简单地重构代码库。最多编译器发出的错误消息仍将使用完整的用范围限定的类型名和长类型名称成为真实的可读性问题。

考虑我经常用来打印类型名称以进行调试的这段代码模板:

struct Foo
{
struct Bar {};
};

typedef Foo::Bar ImportedBar;

// refactored bar
struct Bar {};

template <typename> struct print;

int main()
{
print<ImportedBar> x; // error: aggregate ‘print<Foo::Bar> x’ has incomplete type and cannot be defined
print<Bar> y; // error: aggregate ‘print<Bar> y’ has incomplete type and cannot be defined
return 0;
}

第一个版本仍然打印全名。这可能看起来像对你来说没什么,但考虑一下如果这是一个std::vector 带有模板默认参数等等。突然每个字符都有助于阅读。

关于c++ - 关于命名空间、类和作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13840867/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com