简体   繁体   English

错误:非法将此类型用作表达式。 C ++

[英]Error: illegal use of this type as an expression. C++

I have created a static member function within the class Node, and want to invoke that function with some argument. 我已经在类Node中创建了一个静态成员函数,并希望使用一些参数来调用该函数。 How do I invoke that function in my main function? 如何在主函数中调用该函数?

class Node;
typedef shared_ptr<Node> SharedNode;

class Node {
    Node* parent;
    vector< SharedNode > children;
    int value;

    //limiting construction
    Node(int a_value):value(a_value),parent(0){}
    Node(const Node &copy); //non-construction-copyable
    Node& operator=(const Node& copy); //non-copyable
public:
    static SharedNode create(int a_value){
        return SharedNode(new Node(a_value));
    }
    SharedNode addChild(SharedNode child){
        child->parent = this;
        children.push_back(child);    // First there is a typo here. (nodes.push_back     is incorrent)
        return child;
    }


int main(){

    SharedNode a1 = Node.create(1);
    SharedNode b1 = Node.create(11);
    SharedNode b2 = Node.create(12);
    SharedNode b3 = Node.create(13);
    SharedNode b21 = Node.create(221);
    a1.get()->addChild(b1);
    a1.get()->addChild(b2);
    a1.get()->addChild(b3);
    b2.get()->addChild(b21);
    b2.get()->getNode(221);


    int hold;
    cin>>hold;
}

It gives me a Error: illegal use of this type as an expression. 它给我一个错误:非法使用此类型作为表达式。 Thank you guys! 感谢大伙们!

Statics are accessed using the :: operator not . 使用:: 运算符 not访问静态变量. so it should be Node::Create 所以应该是Node::Create

Use: 采用:

Node::create(1)

to call the function 调用函数

Static member functions or Static Data members are just one copy for the whole class and no separate copies for each instances. 静态成员函数或静态数据成员只是整个类的一个副本,而每个实例没有单独的副本。

So static members can be accessed only with class name and :: operator. 因此,只能使用类名和::运算符访问静态成员。

. Operator is used with only non static members or instance members. 运算符仅与非静态成员或实例成员一起使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM