如何返回类中私有成员字符串的值
How to return the value of a private member string in a class
我想获取sampleclass
中name
私有字符串的值。
#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
相关文章:
- C++ 字符串类擦除成员函数的时空复杂性
- 无法将字符串数组声明为类成员而不是字符 (C++)
- 使用 const char* 初始化 const ref 字符串成员时幕后会发生什么
- CPPCHECK C++成员函数上的格式字符串
- 无法使用 strcpy 将字符串复制到静态结构成员
- 反转没有循环的字符串,C++中只有 std::string 成员
- 如何删除作为C++联合的成员变量的字符串对象
- 有没有办法把字符串数组成员放在".structurevariable"前面?
- C++-将对象(如字符串)映射到表中成员函数的正确方法
- 将字符串推送到私有成员向量
- 有没有更快的方法从成员函数返回格式化字符串
- 在C++中,从构造函数中将字符串文本分配给成员const char*变量时会发生什么
- 添加字符串类型的类成员会导致调用基类函数而不是子函数
- 分类一个向量,该向量由该类中的成员字符串保存对象
- 如何在C++中将本地字符串数组复制到私有成员字符串数组
- 如何实例化C++成员字符串引用
- 从c++类中获取成员字符串
- 如何将类成员字符串传递给其他类函数时解决"'std::length_error"?
- 将vector中结构体的成员字符串打印到cout流
- 如何返回类中私有成员字符串的值