这个问题让我想知道在类外成员函数定义中完全限定类名(包括全局作用域运算符)是否有用/必需。
一方面,我以前从未见过这样做(正确执行的语法似乎还不清楚)。另一方面,C ++名称查找非常简单,因此可能存在极端情况。
题:
是否曾经有过引入超出成员函数定义的定义
ReturnType (::Fully::Qualified::Class::Name::MemberFunctionName)(...) { ... }
不同于
ReturnType Fully::Qualified::Class::Name::MemberFunctionName(...) { ... }(没有全局作用域::前缀)的情况?
请注意,成员函数定义必须放在封闭类的名称空间中,因此这不是有效的示例。
c++ qualified-name global-scope name-lookup scope-resolution-operator
我有以下 C++ 代码片段:
inline std::vector<std::unique_ptr<xir::Tensor>> cloneTensorBuffer(
const std::vector<const xir::Tensor*>& tensors)
{
auto ret = std::vector<std::unique_ptr<xir::Tensor>>{};
auto type = +::DataType::XINT;
ret.reserve(tensors.size());
for (const auto& tensor : tensors) {
ret.push_back(std::unique_ptr<xir::Tensor>(xir::Tensor::create(
tensor->get_name(), tensor->get_shape(), xir::DataType{type, 8u})));
}
return ret;
}
Run Code Online (Sandbox Code Playgroud)
我对这个说法不太清楚:
auto type = +::DataType::XINT;
Run Code Online (Sandbox Code Playgroud)
+后面的::(范围解析运算符)是什么意思?
我正在看别人的 C++ 代码(注意我对 C++ 不太流利)。
在类中,有一个成员函数:
void ClassYaba::funcname()
{
...
::foo();
...
}
Run Code Online (Sandbox Code Playgroud)
该类的命名空间中没有名为 的成员函数foo,但除此之外,::foo()和foo()(没有前导冒号)之间有什么区别?
我想从函数中访问分配给 main 函数中全局变量的值。我不想在函数中传递参数。
我曾尝试参考不同的堆栈溢出类似问题和 C++ 库。
#include <iostream>
long s; // global value declaration
void output() // don't want to pass argument
{
std::cout << s;
}
int main()
{
long s;
std::cin >> s; // let it be 5
output()
}
Run Code Online (Sandbox Code Playgroud)
我希望输出是,5但它显示0.
在cppreference.com \xe2\x80\x93 \xe2\x80\x9cQualified name Lookup\xe2\x80\x9d上,我发现了这个奇怪的代码示例:
\nstruct C { typedef int I; };\n\ntypedef int I1, I2;\n\nextern int *p, *q;\n\n// Slight modification to prevent linker error\n//struct A { ~A(); };\nstruct A { ~A() {}; };\n\ntypedef A AB;\n\nint main()\n{\n p->C::I::~I(); // The name I after ~ is looked up in the same scope as I before ::\n // (that is, within the scope of C, so it finds C::I)\n\n q->I1::~I2(); // The name I2 is looked up in the same …Run Code Online (Sandbox Code Playgroud) Why are we able to call the showA() method without object? But if I use void A::showA(A& x) in the method definition then I have to call it using A's object, why?
#include <iostream>
class A {
public:
int a;
A() { a = 0; }
void showA(A&);
};
void showA(A& x)
{
std::cout << "A::a=" << x.a;
}
int main()
{
A a;
showA(a);
return 0;
}
Run Code Online (Sandbox Code Playgroud)