gpt4 book ai didi

C++ 模板和影子参数

转载 作者:搜寻专家 更新时间:2023-10-31 00:36:29 25 4
gpt4 key购买 nike

我有一个简单的问题。编译失败是什么原因?

template <class T>
class test
{
T varGoodForNothing;
public:
test()
{ }
test(test<T> & tt)
{
varGoodForNothing = tt.varGoodForNothing;
}
test<T> & operator=(const test<T> & tt)
{
if (this == &tt)
return *this;
test(tt);
return *this;
}
};

编译器错误是:

declaration of test tt shadows a parameter.

最佳答案

标准是怎么说的?

标准说Type (name) 类型的声明与使用Type name 相同,请参见下面的标准引用。

[dcl.meaning] / 6

In a declaration T D where D has the form

( D1 )

The type of the contained declarator-id is the same as that of the contained declarator-id in the declaration T D1.

Parentheses do not alter the type of the embedded declarator-id, but they can alter the binding of complex declarators.

话虽如此,您并未使用名为 tt 的参数调用 test 的复制构造函数,而是编译器认为您正在尝试声明一个test 类型的变量,name tt.


如何解决这个问题?

为了避免 T (D); 被解释为 T d; 的问题,我们必须将 T 括在括号内,例如如下所示。

(test) (tt);

注意:即使代码在提议的更改后可以编译,它也不会按照您的意愿执行,也不会按照您的想法执行。

不是为给定的实例调用 test 的复制构造函数,而是声明一个 test 的匿名实例,该实例用 tt 的值初始化.

构造函数只能从其他构造函数中调用(使用 member initializer list )。

关于C++ 模板和影子参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21763935/

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