【问题标题】:Cannot convert 'this' pointer from 'const Foo' to 'Foo&' error无法将“this”指针从“const Foo”转换为“Foo&”错误
【发布时间】:2014-11-18 00:04:20
【问题描述】:

大家好,我有一个类 Foo,它有一个 fooAddress 成员变量

foo.h 中的代码

Class Foo
{
String fooAddress() const;
void setFooAddress(String fooAddress)
....
String m_fooAddress;
} 

foo.cpp 中的代码

String Foo::fooAddress() const
{
return m_fooAddress;
}

void Foo::setFooAddress(String fooAddress)
{
m_fooAddress = fooAddress;
}

现在我有一个 FooList 类,它有一个 foo 列表

FooList.h 中的代码

class FooList
{
 editFooList(Foo foo,int index);
 ...
 private:
 List<Foo> m_fooArray; 
 }

现在我在 FooList.cpp 中的代码是

void FooList::editFooList(Foo foo, int index)
{
m_fooArray.at(index).setFooAddress(foo.fooAddress());
}

但我得到了错误 错误:C2662:“void Foo::setFooAddress(String)”:无法将“this”指针从“const Foo”转换为“Foo &”

由于我没有将 editFooList 定义为 const 函数,我不确定为什么当我尝试修改 m_fooArray 时编译器会抱怨。有人可以指出我做错了什么吗?

【问题讨论】:

  • 您的 C++ 是否准确地复制到了这篇帖子中?您的代码有foo:: 而不是Foo::。我也在某些地方看到QString 而不是String。您使用的是 Qt 而不是 STL?
  • 还有“editFooList(foo foo, int index);”不应该编译。
  • “Foo”栏浮现在脑海中。
  • 是的,我正在使用 Qt,我现在已经纠正了所有问题
  • 是List&lt;&gt; 和QList&lt;&gt; 的别名。 QList.at() 返回一个常量引用。

标签: c++ c++11 constants


【解决方案1】:

我将代码更改为

void FooList::editFooList(Foo foo, int index)
{
m_fooArray[index].setFooAddress(foo.fooAddress());
}

现在正在编译

【讨论】:

  • 这会复制 foo 对象,看起来效率不高。
猜你喜欢
  • 1970-01-01
  • 2011-01-18
  • 2012-08-17
  • 2013-11-18
  • 2011-09-30
  • 2021-06-11
  • 1970-01-01
  • 2022-01-12
  • 1970-01-01
相关资源
最近更新 更多