【问题标题】:Compiler error: "a nonstatic member reference must be relative to a specific object"编译器错误:“非静态成员引用必须相对于特定对象”
【发布时间】:2021-03-10 14:53:48
【问题描述】:

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

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

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

【问题讨论】:

  • 签名也很奇怪。拥有一个不使用对象自己的数据但在不相关的对象上工作的成员函数违背了首先拥有成员函数的意义。一本好的 C++ 书籍也应该解释这一点。
  • @S.M.你能告诉我代码中的错误吗?
  • @churill 签名是什么意思?
  • 不写newFunction(item a),你可以写newFunction()并直接作用于pricecost。然后使用obj1.newFunction() 而不是item::newFunction(obj1) 调用它。但老实说,此时您会问几个不同的非常基本的问题,并且回答“请看书”的人数将会增加。

标签: c++ c++11 c++14


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    这是你的答案:-

    错误信息:

    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++

    【讨论】:

    • 这里为什么使用 .运算符而不是范围解析运算符?
    • 你能解释一下范围解析运算符和点运算符之间的区别以及我们必须使用哪一个吗?
    猜你喜欢
    • 2013-03-19
    • 1970-01-01
    • 2016-08-13
    • 2021-05-30
    • 2018-10-23
    • 2015-06-01
    • 2018-03-26
    相关资源
    最近更新 更多