创建指向对象的指针"this"
Create pointer to "this" object
我在一个项目中似乎遇到了问题,试图创建一个指向"this"的指针,其中"this"是C++中列表中的第一个LinkedList。第一个对象有数据,第二个有。。。直到CCD_ 1是CCD_ 2
编译器向我吐出了这样的话:
linkedlist.hpp:55:22: error: invalid conversion from âconst LinkedList<int>* constâ to âLinkedList<int>*â [-fpermissive]
我做错了什么?
template <typename T>
int LinkedList<T>::size() const
{
int count = 0;
LinkedList* list = this; // this line is what the compiler is complaining about
//adds to the counter if there is another object in list
while(list->m_next != NULL)
{
count++;
list = list->m_next;
}
return count;
}
成员函数标记为const
。这意味着this
也是const
。你需要做:
const LinkedList<T>* list = this; // since "this" is const, list should be too
// ^
// |
// Also added the template parameter, which you need, since "this"
// is a LinkedList<T>
更改
LinkedList* list = this;
至
const LinkedList<T>* list = this;
^^^^^ ^^^
由于函数定义为const
,因此this
指针自动为类型的const LinkedList<T>*
因此,您不能将this->m_next
0指针分配给非const
指针,从而解释错误。
如果您尝试非int
参数,丢失的<T>
可能会给您带来错误。
尝试更改
LinkedList* list = this; // this line is what the compiler is complaining about
至
LinkedList<T> const * list = this;
^^^ ^^^^^
相关文章:
- 为什么使用 "this" 指针调用派生成员函数?
- 关于C++中具有多重继承"this"指针的说明
- Doees the 'this' 指针参与虚函数的多态行为
- 指针'this+1' C++中指的是什么?
- 为什么使用指向函数的指针调用虚函数时不需要指针"this"?
- Lambda 函数捕获错误的指针"this"
- 调用类的方法时,类的指针"this"变为 null C++
- 指针'this'可以是共享指针吗?
- 如何在C++中为指针'this'赋值
- C++:指针"this"没用吗?
- 指针"this"有什么问题?
- 将指针'this'传递为 LPARAM
- 错误 C2663:指针'this'重载没有合法转换
- C++ : 了解指针"this"
- 更改对象的指针'this'以指向不同的对象
- C++编译器是为所有成员方法生成指针"this"还是仅为引用成员的方法生成指针?
- 使用指针和不使用指针"this"有区别吗?
- 将enable_shared_from_这个基于类的指针(this)存储在itelf中
- 创建指向对象的指针"this"
- 如何在类中取消初始化指针"this"?