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

问题描述

我一直在努力学习如何在 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;
}

谁能告诉编译器为什么会给出错误“非静态成员引用必须相对于特定对象”。

此外,有人能说出 ::(范围解析运算符)和使用 .(点运算符)访问类元素之间的区别吗?我对两者有点困惑,谷歌搜索差异并没有带来任何匹配的结果。

解决方法

这是你的答案:-

错误信息:

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

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

我在主函数中创建了一个名为 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

在命名类时不使用驼峰命名也不是一个好习惯,所以请记住:)

这是你的答案 What is the difference between "::" "." and "->" in c++

,

cout << item::newFunction(obj1);这仅在您将 newFunction() 声明为 static 时才有效。 否则,如果要调用成员函数,则必须创建一个对象。 item Obj; 然后调用 Obj.newFunction(obj1);