如何返回类中私有成员字符串的值

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

本文关键字:成员 字符串 何返回 返回      更新时间:2023-10-16

我想获取sampleclassname私有字符串的值。

#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();
}

你需要在getname()函数中返回一个字符串,因为你的name变量是一个字符串

string getname() {
    return name;
}

通过这样做,您将获得一个新的std::string实例作为rvalue结果,然后将其输出到主函数中的屏幕。

作为另一个想法,与您的问题无关:对于像这样的小程序,全局使用命名空间没有问题,但您应该尽量不习惯它,因为它可能会导致较大项目中不同命名空间内的名称冲突。

#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