简体   繁体   中英

Debugging a simple program in C++

I'm trying to find out what is wrong with my program. It doesn't output my desired output.

Why doesn't it show any errors but doesn't show the output?

#include<iostream>
  using namespace std;

  class DanielClass
  {
  public:
string NameFunction(string first_name, string last_name)
{
    return fullname = first_name + " " + last_name;
}


  private:
string fullname;

};



int main()
{
string namefirst;
string namelast;
DanielClass NameObj;

cout<<"Enter your first name: ";
cin>>namefirst;
cout<<"Enter your last name: ";
cin>>namelast;
cout<<"Your full name is: ";
cout<<NameObj.NameFunction("" , "");

return 0;
}

You need to pass the strings to the function for it to work:

cout<<NameObj.NameFunction(namefirst ,namelast);

Here is an example

You are not passing your names into NameFunction .

cout<<NameObj.NameFunction("" , "");
//                 blank   ^^   ^^

It should read:

cout<<NameObj.NameFunction(namefirst , namelast);

First of all you need to include header <string>

#include <string>

And instead of statement

cout<<NameObj.NameFunction("" , "");

you should write

cout<<NameObj.NameFunction( namefirst , namelast );

As for me I would declare the class the following way

#include <iostream>
#include <string>

class DanielClass
{
public:
    DanielClass( const std::string &first_name, const std::string &last_name )
        : fullname( first_name + " " + last_name )
    {
    }

    std::string GetFullName() const
    {
        return fullname;
    }

private:
    std::string fullname;
};

And main will look like

int main()
{
    std::string namefirst;
    std::string namelast;

    std::cout << "Enter your first name: ";
    std::cin >> namefirst;

    std::cout << "Enter your last name: ";
    std::cin >> namelast;

    DanielClass NameObj( namefirst, namelast );

    std::cout << "Your full name is: ";
    std::cout << NameObj.GetFullName() << std::endl;

    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM