【发布时间】: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()并直接作用于price和cost。然后使用obj1.newFunction()而不是item::newFunction(obj1)调用它。但老实说,此时您会问几个不同的非常基本的问题,并且回答“请看书”的人数将会增加。