C++类中的一个问题

来源:百度知道 编辑:UC知道 时间:2024/05/18 01:31:15
#include<iostream>
using namespace std;
class yangchao
{
public:
void mingzi(){cout<<"我的名字是杨超\n";}
void nianling(){cout<<"我的年龄是14岁\n";}
private:
int shengao(){cout<<"我的身高是160厘米";}
};
int main()
{
yangchao tom;
tom.mingzi();
tom.nianling();
tom.shenggao
return 0;

}

我怎样调用私有成员中的shenggao

您好,不能通过类的对象直接调用私有成员(包括私有数据成员和成员函数).
但是可以通过共有成员去调用私有成员及其函数,下面的就是一个例子.

可以通过callShengao函数去调用shenggao函数.
//////
#include<iostream>
using namespace std;
class yangchao
{
public:
void mingzi(){cout<<"我的名字是杨超\n";}
void nianling(){cout<<"我的年龄是14岁\n";}
void callShengao(){shengao();}
private:
void shengao(){cout<<"我的身高是160厘米";}
};
int main()
{
yangchao tom;
tom.mingzi();
tom.nianling();
// tom.shenggao(); //不允许
tom.callShengao();
return 0;

}

成员函数一般设为公有,数据成员一般设备私有,通过成员函数调用数据成员!