首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

【询问】这是咋回事? 多谢

2013-07-16 
【询问】这是怎么回事?谢谢//代码 : #include iostream#include stringusing namespace stdint main ()

【询问】这是怎么回事? 谢谢
【询问】这是咋回事?   多谢

//代码 : 
#include <iostream>
#include <string>
using namespace std;
int main ()
{
class Student
{
public :
void display ();
private : 
int num;
string name;
char sex;
};
void  Student :: display ()
{
cout << "num : " << num << endl;
cout << "name : " << name << endl;
cout << "sex : " << sex << endl; 
}
Student stud1, stud2;

return 0;
}


应该怎么改?
[解决办法]
函数作用域,是不开放的,内部可以定义类型,包括类类型。
但是,不可以,把类的成员函数定义在,类外部---- 函数内部;
当然,也不可以,定义在函数外部;
只能,在类内部,直接定义,不能分开定义。

有以下两个办法,解决这个问题:


//1)类在函数外定义

//代码 : 
 #include <iostream>
 #include <string>
 using namespace std; 
 
 class Student{
 public :
     void display ();
 private : 
     int num;
     string name;
     char sex;
 };
 
void  Student :: display (){
    cout << "num : " << num << endl;
    cout << "name : " << name << endl;
    cout << "sex : " << sex << endl; 
}
int main (){
    Student stud1, stud2;
    return 0;




//2) 函数内部的定义的类,类的成员函数, 全部定义在类的内部,不要分开来声明和定义。
int main (){
    class Student{
    public :
        void display (){


            cout << "num : " << num << endl;
            cout << "name : " << name << endl;
            cout << "sex : " << sex << endl; 
        }
    private : 
        int num;
        string name;
        char sex;
    };
    Student stud1, stud2;
    return 0;

热点排行