This question already has an answer here:
这个问题在这里已有答案:
- Invalid use of 'this' in non-member function 1 answer
在非成员函数1答案中无效使用'this'
I have the error "invalid use of 'this' in non-member function"
我有错误“在非成员函数中无效使用'this'”
What is the correct way to write the code to avoid this error.
编写代码以避免此错误的正确方法是什么。
tree.h:
#ifndef TREE_H
#define TREE_H
template <typename T>
class Node;
class Tree
{
public:
Tree();
template <typename TNodeType>
Node<TNodeType> elaborate(Node<TNodeType> &node);
Tree* self();
void doSomething();
};
template <typename TNodeType>
Node<TNodeType> createNew() {
Node<TNodeType> model(this); //<-- ERROR HERE
return model;
}
#endif // TREE_H
node.h:
#ifndef NODE_H
#define NODE_H
#include <tree.h>
template <typename TNodeType>
class Node
{
public:
Node(Tree *tree);
TNodeType current();
private:
Tree *_tree;
};
template <typename TNodeType>
Node<TNodeType>::Node(Tree *tree):
_tree(tree)
{
_tree->doSomething();
}
template <typename TNodeType>
TNodeType Node<TNodeType>::current()
{
//some code here
}
#endif // NODE_H
Solved.
In tree.h I skipped the declaration of:
在tree.h中,我跳过了以下声明:
template <typename TNodeType>
Node<TNodeType> createNew();
And I had forgotten in the definition "Tree::" before "createNew()"
我在“createNew()”之前忘记了“Tree ::”这个定义
I agree that this question could have been avoided ;-). Sorry
我同意这个问题可以避免;-)。抱歉
2 个解决方案
#1
4
createNew()
is a free function (i.e. not a member of a class), and therefore has no notion of this
.
createNew()是一个*函数(即不是类的成员),因此没有这个概念。
#2
2
template <typename TNodeType>
Node<TNodeType> createNew() {
Node<TNodeType> model(this); //<-- ERROR HERE
return model;
}
It's really no member function. this
is keyword of C++ language, that can be used only in member functions.
它真的没有会员功能。这是C ++语言的关键字,只能在成员函数中使用。
#1
4
createNew()
is a free function (i.e. not a member of a class), and therefore has no notion of this
.
createNew()是一个*函数(即不是类的成员),因此没有这个概念。
#2
2
template <typename TNodeType>
Node<TNodeType> createNew() {
Node<TNodeType> model(this); //<-- ERROR HERE
return model;
}
It's really no member function. this
is keyword of C++ language, that can be used only in member functions.
它真的没有会员功能。这是C ++语言的关键字,只能在成员函数中使用。