如何从类调用函数 - 错误"was not in the scope"



这是我的程序,它导致下面提到的汇编错误:

#include <iostream>
using namespace std;
class weight{
    private:
        float current_weight, diet_weight, num_exercise;
        int num_meal,i;
    public:
        // make users to enter current weight
        void get_curent_weight()
        {
            cout<<"Please enter your current weight: "; 
            cin>>current_weight;
        }
        void enter_data()
        {
            for (i=1; i>7; i++)
            {
                cout<<"Day "<<i<<endl;
                cout<<"--------------"<<endl;
                // Number of Meal(s)
                cout<<"Number of meal(s) you eat today: ";
                cin>>num_meal;
                cout<<endl;
                // Number of Exercise
                cout<<"Number of hour(s) you spent on exercises today: ";
                cin>>num_exercise;
                cout<<endl;
            }
        }
        // output the information
        void information()
        {
            // calculate the final weight
            diet_weight=current_weight+(0.5*num_meal)-(num_exercise/3)*0.5;
            cout<<"Your weight after 7 days diet: "<<diet_weight<<endl;
        }
};
int main(){
    get_curent_weight();
    enter_data();
    information();
    return(0);
}

我得到以下汇编错误

error: 'get_curent_weight' was not declared in this scope
error: 'enter_data' was not declared in this scope
error: 'information' was not declared in this scope

看来我以错误的方式称之为函数。感谢您阅读我的问题,作为C 的初学者,我感谢它。:))

您需要创建类的实例,并在该实例上调用成员函数:

int main() {
    weight my_weight;
    my_weight.get_curent_weight();
    my_weight.enter_data();
    my_weight.information();
    return 0;
}

可以称为蓝图;它的函数只能在功能属于的类的对象上实现。该功能不能称为独立。要解决错误,您需要使用数据类型weight在Main()函数中声明对象,然后用该创建的对象调用该函数。这样的例子就像:

weight object_name;
object_name.get_curent_weight();
object_name.enter_data();
object_name.information();

另外,您可以将功能从班级中取出;这样,它们可以在没有weight类的对象的情况下使用。这将在我建议的首选方面花费更多的努力。

相关内容

最新更新