这个程序出了什么问题?说a和b不在范围内

What is wrong with this program? Says a and b are not in the scope

本文关键字:范围内 程序 问题 什么      更新时间:2023-10-16

编译器说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;

变量ab是类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();