2014-10-08 74 views
-2

我想输出私人班级成员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;  
} 
+0

问题是什么?你可以用这种方法设置数值,但它不会告诉你他们最初是什么 – chrisb2244 2014-10-08 17:12:24

+0

我不明白这一点。代码中的任何内容都不会尝试检索私有成员的值。 – 2014-10-08 17:15:21

+0

看,我所需要的只是这一行cout << theCode <<“\ n”<< theName;但正如你所看到的,我无法打印出BankCode和Agent的名字,只是将它们打印在屏幕上没有别的,我的问题是为什么它适用于int而不是字符串或字符?为什么我不能用字符串类型访问类中的私有? – babylon 2014-10-08 17:45:22

回答

1

第三个答案

你的代码中有两个“吸气”风格的功能,但没有一个不带任何参数。也就是说,你的两个函数都需要传递参数。

您的主要功能是调用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

+0

请所有我需要打印银行代码和代理名称,但它不会编译,它就像我无法访问他们?我不明白,它适用于整数,但不是字符串或字符,请帮助 – babylon 2014-10-08 17:50:36

+0

编辑以反映您的请求 - 如果这是你想说的话,我会整理。 – chrisb2244 2014-10-08 17:56:25

+0

你知道吗?我正在学习C++,我想从逻辑上理解它,我知道其他方法来显示这些代码并且可以工作,但我只想知道我的错误在哪里,它有什么问题,Return-Type class-name ::函数名(参数声明){函数体},这应该工作,但为什么不工作与我? – babylon 2014-10-08 18:11:13