类功能定义但不称为(C )

Class function is defined but not to be called(C++)

本文关键字:功能 定义      更新时间:2023-10-16

我想从" Hello"中调用公共功能,但是此错误不会让我。请告诉我我在做什么错?

这是代码:

#include <iostream>
using std::cout;
using std::cin;
using std::string;
class hello {
    public: 
        void sayit(){
            cout << "Hello, World!";
        }
    };
int main(){
    string str;
    cout << "Type in "start":";
    cin >> str;
    if (str == "start"){
//this is where the error happens.
        hello.sayit();
    }
}

这是错误:

[错误]预期'。令牌

您需要制作sayIt() static或声明hello对象,然后调用method。静态方法看起来像static void sayIt(),您将其称为hello.sayIt(),因为静态方法不需要类的实例才能工作。如果使用hello对象,则将像此hello x; x.sayIt()一样完成。

void sayit()定义了类成员函数。

要调用类成员函数,您需要类的实例。

hello hello_instance;
hello_instance.sayit();

作为替代方案,您可以将sayit更改为静态功能。静态功能是类的成员,但不需要类的实例。结果,this变量在static方法中不存在,而非静态成员变量无法使用。

static void sayit(){
    cout << "Hello, World!";
}

不使用任何成员变量,可以使用

来调用
hello::sayit();