我一直在学习C++,而且我目前正在练习课程.我创建了一个存储播放器名称和分数的类,并定义了操作数据并显示它的函数.
我创建的一个功能是比较两个玩家的得分并返回指向具有较高得分的玩家的指针.这是功能:
Player * Player::highestScore(Player p2)const
{
if(p2.pScore>pScore)
{
return &p2;
}
else
{
return this;
}
}
Run Code Online (Sandbox Code Playgroud)
从主要我创建以下球员:
Player p1("James Gosling",11);
Player *p4 = new Player("Bjarne Stroustrup",5);
Run Code Online (Sandbox Code Playgroud)
我称之为最高分数函数:
Player *highestScore = p1.highestScore(*p4);
Run Code Online (Sandbox Code Playgroud)
但是,您可能已经注意到从函数本身读取,当我将指针返回到调用该方法的对象时(如果它具有更高的分数),我得到一个错误,指出:
return value type does not match the function type
Run Code Online (Sandbox Code Playgroud)
当我将函数的返回类型声明为a时const,这个问题似乎消失了,如下所示:
const Player * Player::highestScore(Player p2)const
Run Code Online (Sandbox Code Playgroud)
令我困惑的部分是为什么它允许我return &p2,哪些不是const,也不允许我返回this,这是一个指向调用该函数的对象的指针,这不是一个const好的?即使我将函数返回类型声明为const,它仍然允许我return &p2,即使传递给参数的参数不是const Player对象?
对不起,如果这个问题看起来很奇怪,或者我正在尝试做的是非常糟糕的编程,但这只是为了通过这样做来学习.
令我困惑的部分是为什么它允许我返回&p2,它不是const而且不允许我返回它,这是一个指向调用函数的对象的指针,它也不是const ?
this 是 const(或者,更准确地说,是指向成员函数的指针const)const,就像所有数据成员一样:
#include <iostream>
#include <type_traits>
struct A
{
void foo()
{
std::cout << std::is_same<decltype(this), const A*>::value << '\n';
}
void bar() const
{
std::cout << std::is_same<decltype(this), const A*>::value << '\n';
}
};
int main()
{
A a;
a.foo();
a.bar();
}
Run Code Online (Sandbox Code Playgroud)
输出:
0
1
Run Code Online (Sandbox Code Playgroud)
即使我将函数返回类型声明为const,它仍然允许我返回&p2,即使传递给参数的参数不是const Player对象?
我们看不到你尝试过的东西,但可能是它Player* const,它与Player const*(或const Player*)不一样.您可以添加const内斯到&r2就好了; 把它const带走是一个不同的故事.