How to return the value of a private member string in a class [closed]

StackOverflow https://stackoverflow.com/questions/22818942

  •  26-06-2023
  •  | 
  •  

سؤال

I want to get the value of a private string name in sampleclass.

#include <iostream>
#include <string>

using namespace std;

class sampleclass {
public:
    int getname(){ //this is my attempted getter
    string x = name;
    }
private:
    string name= "lance"; //this is the private I want returned by value

};

int main(){    
    sampleclass object;
    cout << object.getname();
}
هل كانت مفيدة؟

المحلول

You need to return a string in your getname() function, since your name variable is a string

string getname() {
    return name;
}

By doing so, you get a new instance of std::string as an rvalue result, which is then outputted to the screen in your main function.

As another thought, not related to your problem though: there is no problem in using a namespace globally for small programs like this one, but you should try to not get used to it because it can lead to name conflicts within different namespaces in bigger projects.

نصائح أخرى

#include <iostream>
#include <string>

using namespace std;

class sampleclass{
public:
    sampleclass() : name("lance") { }
    string getname(){ // return a string (not an int)
       return name;
    }
private:
    string name;

};
int main(){

    sampleclass object;
    cout << object.getname();

}

g++ test.cpp && ./a.out lance

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top