如何使用成员函数访问私有字符串变量?

时间:2014-10-08 17:06:43

标签: c++ function member

我想输出私有类成员BankcodeAgentName的值。如何在我的main()函数中执行此操作,或者通常在BOURNE类之外执行此操作。

我的初始代码尝试如下:

#include <iostream>
#include <string>
using namespace std;

class BOURNE
{
    string Bankcode ={"THE SECRET CODE IS 00071712014"} ; /*private by default*/

    string AgentName={"Jason Bourne"};                   /*private by default*/
public:    
    void tryToGetSecretCodeandName(string theName ,string theCode);    //trying to get the private   

    void trytoGetAgentName( string name); // try to get name
};
//***********************defining member function**************************************

void BOURNE::tryToGetSecretCodeandName(string theName, string theCode)  //member defining function
{
   Bankcode=theCode;    //equalling name to the code here 

   AgentName=theName;   //the samething here

   cout<<theCode<<"\n"<<theName; //printing out the values
}
//************************main function*****************************
int main()
{
   BOURNE justAnyObject;  //making an object to the class
   justAnyObject.tryToGetSecretCodeandName();
   return 0;    
}

1 个答案:

答案 0 :(得分:1)

第三次回答

你的代码中有两个“getter”&#39;样式函数,但没有人不参数。也就是说,你的两个函数都需要传递参数。

你的主要功能是调用get...CodeandName(),它没有参数。因此,您会收到编译器错误,可能会抱怨有效签名或传递的参数。

已编辑的答案 如果您只想获取值,那么典型的(据我所知)实现就像

std::string BOURNE::getCode()
{
    return Bankcode;
}

std::string BOURNE::getName()
{
    return AgentName;
}

int main()
{
    BOURNE myAgent;
    cout<< "The agent's name is : " << myAgent.getName() << endl;
    cout<< "The agent's code is : " << myAgent.getCode() << endl;
}

原帖,留下来因为我觉得它更有用

我怀疑你提出的问题是你能否做到像

这样的事情
void BOURNE::tryToGetSecretCodeandName(string theName, string theCode)
{
    if (Bankcode == theCode) {
        cout<< "You correctly guessed the code : " << Bankcode << endl;
    }
    if (AgentName == theName) {
        cout << "You correctly guessed the agent's name : " << AgentName << endl;
    }
}

这将允许您反复猜测名称,并在您纠正时获得输出。

如果你想禁用这种猜测,那么你可以考虑创建一个新类(可能是基于std::string派生的 - 但是看看this question是出于小心的原因!)并实现operator==函数始终返回false

相关问题