#include "stdafx.h"
#include <iostream>
#include <string>
usingnamespace std;
class WhatThe
{
public:
void settankName(string name)
{
tankName = name;
}
string gettankName()
{
return tankName;
}
void displayMessage()
{
cout<< "welcome to the Tank Museum\n"<<gettankName()<<endl;
}
private:
string tankName;
};
int main()
{
string nameofTank;
WhatThe myTank;
cout<<"Initial tank name is: "<<myTank.gettankName()<<endl;
cout<<"\nPlease enter the tanks name: "<<endl;
getline( cin, nameofTank);
myTank.settankName (nameofTank);
cout<<endl;
myTank.displayMessage();
return 0;
}
But if l change the last statement before "return 0;", to "myTank.gettankName()"
rather than "myTank.displayMessage();" , it comes out that the name l entered
could not appear in the console just like the "initial tank name is"...
However, l wonder why the displayMessage() function will output the name l entered on the screen just by the "<<gettankName()<<" but the former cannot?
Printing means that you make something visible on the screen. This is what std::cout is used for.
Returning is something you do to pass information from a function back to where the function was called from. The returned value can be used for anything you want, but you need to write the code for it to happen.
Some examples:
1 2 3 4 5 6 7 8 9 10 11
// print the name
std::cout << myTank.gettankName();
// store the name in a variable
std::string name = myTank.gettankName();
// pass the name as argument to another function
if (!validName(myTank.gettankName()))
{
std::cout << "Invalid tank name!\n";
}