类中私有成员的访问问题 急

来源:百度知道 编辑:UC知道 时间:2024/06/30 01:43:18
#include <stdio.h>
#include <iostream>
using namespace std;

class test1 {
public:
test1(int n)
{num=n;}
private:
int num;
};

class test2 {
public:
explicit test2 (int n)
{num=n;}
private:
int num;
};

int main()
{
test1 t1=12;
//test1 t2=(13);
test2 t3(14);
//test2 t4=15;
cout <<t1.num<<endl
//<<t2.num<<endl
<<t3.num<<endl
//<<t4.num<<endl;
return 0;

}

用面向对象的观点这个问题应该是这样解决的(我前面这句有点乎悠^o^):

#include <stdio.h>
#include <iostream>
using namespace std;

class test1 {
public:
test1(int n){num=n;};
inline void output() { cout<<num<<endl;};
private:
int num;
};

class test2 {
public:
explicit test2 (int n)
{num=n;};
inline void output() { cout<<num<<endl;};
private:
int num;
};

int main()
{
test1 t1(12);
test2 t3(14);
t1.output();
t3.output();
return 0;

}

C++规定:访问私有数据只能通过公有函数进行。因此,要想在主程序中输出私有数据的值,只能通过对象调用公有函数。你需要再在两个类中分别定义显示私有数据的公有函数!!!