如何在类外编写函数的代码?c++

How to write the code of a function outside the class? c++

本文关键字:函数 代码 c++      更新时间:2023-10-16

我是 c++ 的新手,我正在学习类和对象。在类中,我定义了一个函数,我想在类中编写它的代码。 我认为应该是这样的:

#include <iostream>
using namespace std;
class student{
public:
string name;
int mark1, mark2;
float calc_media(int, int);
void disp(){
cout << "Student:" << name << endl;
cout << "Media:"<< calc_media(int, int) << endl;
}

};
student::float calc_media(int x, int y){
float media = (x + y)/2.0; 
return media; 
}

int main (){
student peter;
cout <<"name:" ;
cin>>peter.name;
cout <<"mark1:" ;
cin>>peter.mark1;
cout <<"mark2:" ;
cin>>peter.mark2;
cout <<"media:" << peter.calc_media(peter.mark1, peter.mark2) << endl << endl;
peter.disp();
return 0;
}

谁能帮助我,因为它不起作用。它显示以下错误:expected primary expression before 'int'在第 13 行,expected unqualified-id before 'float'在第 19 行。

return_type class_name::member_function_name(parameters)
{
//action
}

在您的情况下:

float student::calc_media(int x, int y)
{
float media = (x + y)/2.0; 
return media; 
}

在你的课堂上改变这个

cout << "Media:"<< calc_media(int, int) << endl;

cout << "Media:"<< calc_media(mark1, mark2) << endl;

您的示例中有两个简单的拼写错误。

cout << "Media:"<< calc_media(int, int) << endl;

必须在此处传递两个值,而不是类型。所以你可以写

cout << "Media:"<< calc_media(2, 2) << endl;

这就是编译器拒绝此程序的原因。
除此之外,您的代码中还有另一个拼写错误,在修复第一个后会遇到:

student::float calc_media(int x, int y){
float media = (x + y)/2.0; 
return media; 
}

这也是一定是错别字

float student::calc_media(int x, int y){
float media = (x + y)/2.0; 
return media; 
}