gpt4 book ai didi

c++ - 什么时候应该使用this->?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:17:20 25 4
gpt4 key购买 nike

我想知道这个->是否应该同时使用:

void SomeClass::someFunc(int powder)
{
this->powder = powder;
}

//and
void SomeClass::someFunc(bool enabled)
{
this->isEnabled = enabled;
}

我想知道后者是否是正确的必要条件,或者 isEnabled = enabled 是否就足够了。

谢谢

最佳答案

this->

在直接使用成员会产生歧义时需要。这可能发生在模板代码中。

考虑一下:

#include <iostream>

template <class T>
class Foo
{
public:
Foo() {}
protected:
void testing() { std::cout << ":D" << std::endl; }
};

template <class T>
class Bar : public Foo<T>
{
public:
void subtest() { testing(); }
};

int main()
{
Bar<int> bar;
bar.subtest();
}

这将失败,因为调用 testing() 依赖于模板参数。说你的意思是你必须做的功能this->testing();Foo<T>::testing();

错误信息:

temp.cpp: In member function ‘void Bar<T>::subtest()’:
temp.cpp:16:32: error: there are no arguments to ‘testing’ that depend on a template parameter, so a declaration of ‘testing’ must be available [-fpermissive]
temp.cpp:16:32: note: (if you use ‘-fpermissive’, G++ will accept your code, but allowing the use of an undeclared name is deprecated)

关于c++ - 什么时候应该使用this->?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4491234/

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