C++ 这个程序有什么问题?表示a和b不在范围内

C++ 这个程序有什么问题?表示a和b不在范围内,c++,C++,编译器表示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 ar

编译器表示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;
}
#包括
使用名称空间std;
类样本{
私人:
INTA,b;
公众:
void setvalue(){
a=25;b=40;`在这里输入代码`
}
friend int sum(示例s1);//表示a和b不在范围内
};
整数和(样本s1){
返回a+b;//表示a和b不在范围内
}
int main(){
样本x;
x、 setvalue();
不能改变:

return a+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”-变量已经在作用域中,因为它们与函数(类作用域)在同一作用域中。因此,您可以重写该类:

将以下内容添加到类的“公共”下:

int sum()
{
    return a + b;
}
总的来说:

cout << "\nSum" << x.sum();

cout越过可怕的编辑(请修复),它看起来像是您试图在全局函数(
sum
)中访问
a
b
)。你想用谁的
a
b
呢?你需要一个
sample
的实例。你是想用
s1.a
等吗?在你修复代码之前,你需要多次否决票,这目前是毫无意义的。为什么不在类中定义sum?因为这样它就不再是一个自由函数了,我想OP需要一个fr我认为sum(x)是正确的。对于x,sum()编译器给出error@Nareshjungshahi我的意思是,如果您将我编写的函数添加到类中,那么
x.sum()
就可以了。顺便说一句,如果可以,请将其标记为答案。
cout << "\nSum" << x.sum();