我想输出私人班级成员Bankcode
和AgentName
的值。我如何从我的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;
}
问题是什么?你可以用这种方法设置数值,但它不会告诉你他们最初是什么 – chrisb2244 2014-10-08 17:12:24
我不明白这一点。代码中的任何内容都不会尝试检索私有成员的值。 – 2014-10-08 17:15:21
看,我所需要的只是这一行cout << theCode <<“\ n”<< theName;但正如你所看到的,我无法打印出BankCode和Agent的名字,只是将它们打印在屏幕上没有别的,我的问题是为什么它适用于int而不是字符串或字符?为什么我不能用字符串类型访问类中的私有? – babylon 2014-10-08 17:45:22