gpt4 book ai didi

c++ - "Using"类内指令

转载 作者:行者123 更新时间:2023-11-28 05:50:44 26 4
gpt4 key购买 nike

继我之前的 question .我已经决定使用 using 指令在我的类中为类型设置别名,以避免导入其他内容并污染使用这些有问题的 header 的其他 header 。

namespace MyLibrary {
namespace MyModule1 {
class MyClass1 {
public:
float X;
float Y;

MyClass1(float x, float y): X(x), Y(y) {}
};
} // namespace MyModule1

namespace MyModule2 {
class MyClass2 {
private:
// as suggested in linked question
using MyCustomType1 = MyLibrary::MyModule1::MyClass1;

public:
void DoSomething(MyCustomType1 parameter) {
std::cout << parameter.X << std::endl;
std::cout << parameter.Y << std::endl;
}
};
} // namespace MyModule2
} // namespace MyLibrary

int main(int argc, char* argv[])
{
MyLibrary::MyModule1::MyClass1 some_parameter(1.0f, 2.0f);
MyLibrary::MyModule2::MyClass2 some_var;

// Can't do this
// MyLibrary::MyModule2::MyClass2::MyCustomType1 some_other_var;

// But I can do this
some_var.DoSomething(some_parameter);
return 0;
}

MyLibrary 命名空间之外的用户如何知道什么是 MyCustomType1 如果它在一个类中(私下)别名?

我在这里使用 using 是合法的,还是我不小心做了一个肮脏的 hack?

最佳答案

他们会知道您必须#include 两个类的声明的简单原因。

读完这篇文章和上一个问题后,我认为这里缺少的概念是前向声明的概念。

考虑以下头文件,我们称此文件为 mymodule1_fwd.H:

namespace MyLibrary {
namespace MyModule1 {
class MyClass1;
} // namespace MyModule1
}

就是这样。这足以让您声明 MyClass2:

#include "mymodule1_fwd.H"

namespace MyModule2 {
class MyClass2 {
private:
// as suggested in linked question
using MyCustomType1 = MyLibrary::MyModule1::MyClass1;

public:
void DoSomething(MyCustomType1 parameter);
};
} // namespace MyModule2

请注意,仅包含此头文件不会真正自动获取整个 MyModule 类声明。另请注意以下事项:

您不能定义内联 DoSomething() 类方法的内容,因为它实际上使用别名类型。这会产生以下后果:

  • 您必须在某个地方以某种方式定义 DoSomething() 方法,可能在 .C 实现翻译模块中。

    <
  • 同样,您必须从 mymodule1_fwd.H 头文件中声明实际的 MyClass1 类。我在这里使用我自己的个人命名约定,“filename_fwd.H”用于前向声明,前向声明头文件;和“filename.H”为实际的类实现,实现头文件。

  • DoSomething() 方法的调用者必须显式#include MyClass 的实际类声明头文件,因为他们必须将其作为参数传递。

您无法真正避免这样一个事实,即调用者必须知道他们实际用来传递参数的类。但只有 DoSomething() 方法的调用方才需要它。使用 MyClass2 其他部分的东西,不调用 DoSomething(),不需要了解 MyClass1 的任何信息,并且除非他们显式#include 类实现头文件,否则他们看不到实际的类声明。

现在,如果您仍然需要内联 DoSomething(),出于性能原因,可以使用一些技巧,使用预处理器指令,如果有人 #include 包含所有必需的头文件,它们将获得 DoSomething() 方法的内联声明。

但这必须是另一个问题。

关于c++ - "Using"类内指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35306269/

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