这个程序出了什么问题?说a和b不在范围内
What is wrong with this program? Says a and b are not in the scope
编译器说a和b没有在作用域中声明
#include <iostream>
using namespace std;
class sample {
private:
int a, b;
public:
void setvalue() {
a=25; b=40;`enter code here`
}
friend int sum(sample s1); //says a and b are not in the scope
};
int sum(sample s1) {
return a+b; //says a and b are not in the scope
}
int main() {
sample x;
x.setvalue();
cout<<"nSum ="<<sum(x);
return 0;
}
更改:
return a+b;
至
return s1.a+s1.b;
变量a
和b
是类sample
的成员。这意味着这些变量必须作为sample
现有实例的一部分使用.
运算符进行访问:
return a + b; // Tries to find variables named 'a' and 'b', but fails (error)
return s1.a + s1.b; // Uses the members of s1, finds them, and works correctly
但是,在类的成员函数中,不需要使用"s1"-变量已经在作用域中,因为它们与函数(类作用域(在同一作用域中。所以你可以重写类:
在public下将以下内容添加到类中:
int sum()
{
return a + b;
}
总的来说:
cout << "nSum" << x.sum();
相关文章:
- 为什么在全局范围内使用"extern int a"似乎不行?
- 错误:未在此范围内声明'reverse'
- 并行用于C++17中数组索引范围内的循环
- 求出有多少个数字是完美平方,而sqrt()是L,R范围内的素数
- 不计算一个范围内的完美数
- 错误:"imread"未在此范围内声明
- 我在范围内未声明的错误类有问题
- 如何在cpp中使用地图显示给定日期范围内(在下面的问题中)的费率?
- 我有一个数组,我想输入一个范围,然后找到范围内所有偶数的总和?
- 未在此范围内声明错误 'xy'
- 在C++中使用变量而不是"#define"来指定数组大小是不是一种糟糕的做法?(C错误:在文件范围内
- 命名空间范围内的外部 - GCC vs clang vs msvc
- 全局范围内的对象会导致程序退出时崩溃
- 以下程序中最大 int 1000 000(在 int 范围内)的整数溢出
- 编写一个程序,该程序在0-99范围内生成10000个随机整数,并从随机数据中产生直方图
- RSA程序只对特定范围内的数字进行加密和解密
- 编写程序生成1000个0-49范围内的随机整数.(c++)
- 这个程序出了什么问题?说a和b不在范围内
- 当C++试图访问向量的元素(在范围内)时,Qt Quick Windows应用程序崩溃
- C++ - "My_Array"未在此范围内声明 - 简易程序