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