提问者:小点点

编译器错误:“非静态成员引用必须相对于特定对象”


我一直在尝试学习如何在CPP中的类中声明函数:

这是我写的程序:

    //Passing object as function arguments and returning objects
#include <iostream>
using namespace std;
class item{ //Function can be declared either within the class (in that case, there is no need of making the data private)
    int price;
    float cost;
    public:
    int newFunction(item a){
        a.cost=10;
        a.price=40;
        return a.cost;
    }
} obj1;
int main(){
    cout << item::newFunction(obj1);
    return 0;
}

有人能说出为什么编译器给出错误“一个非静态成员引用必须是相对于一个特定对象的”。

还有,有人能说出::(作用域解析运算符)和使用.(点运算符)访问类元素之间的区别吗。我有点搞不清这两者之间的区别,谷歌搜索这个区别并没有带来任何匹配的结果。


共2个答案

匿名用户

COUT<这仅当您将NewFunction()声明为Static时才起作用。否则,如果要调用成员函数,就必须创建一个对象。项obj;然后调用obj.newFunction(obj1);

匿名用户

这是你的答案:-

错误消息:

14:35: error: cannot call member function 'int item::newFunction(item)' without object

你不能只调用一个类函数而不创建它的任何对象,因为如果类函数不是先在RAM中创建的,你就不能直接访问它,这就是为什么我们要创建一个类的对象。

我在main函数中创建了一个临时对象obj2,它可以正常工作。

这是增加的一行

#include <iostream>
using namespace std;

class Item { //Function can be declared either within the class (in that case, there is no need of making the data private)
    int price;
    float cost;

public:

    int newFunction(item a) {
        a.cost=10;
        a.price=40;
        return a.cost;
    }

} obj1;
int main() {
    Item obj2;
    cout << obj2.newFunction(obj1);
    return 0;
}

输出:

10

另外,在命名类时不使用camelcase也不是一个好的做法,所以请记住这一点:)

这是你的答案“::”“之间的区别是什么。”和“->”