如何在类外编写函数的代码?c++
How to write the code of a function outside the class? c++
我是 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;
}
相关文章:
- 如何将 c++ get 函数代码转换为 opencv 算法中使用的 python
- 修改链表主函数代码,用户将在其中输入节点的索引和数据以及正确的消息
- 是否可以像这样编写c malloc函数代码
- 函数范围的静态变量如何导致与共享库中函数代码的未来使用不兼容
- 如何将C++ lambda 函数代码转换为 C#?
- 该构造函数代码如何将指针作为参数
- 调用C++具有复杂参数和复杂返回类型的函数 C 代码
- "_FCbuild"不能用作函数 - C/C++ 代码错误
- 复制赋值和复制构造函数(代码C++的差异)
- 反向链表的递归函数(代码段说明)
- 当满足条件时,是否可以在 GLSL 着色器中回调 C/C++ 函数/代码
- 在构造函数代码之前禁用默认类成员初始化
- 以下移动构造函数代码安全吗?
- C++构造函数代码..这叫什么
- 如何更改SWIG生成的CSHARP文件中的构造函数代码
- 找不到当前函数(代码::块)C++的边界
- 使用模板进行 C++ 函数代码泛化
- 编写此指针函数代码的长格式方法是什么
- C++某些构造函数代码之间的区别
- 错误C2668从站点对重载函数代码的调用不明确http://h264bitstream.sourceforge.net/