如何在c++中返回类中对象的字符串
How can I return a String of an object in a class in c++?
我想访问一个字符串,这个字符串是我的类的一部分,但我似乎无法使它工作。下面是示例代码:
#include<iostream>
#include<string>
#include<vector>
class element {
std::string Name;
int Z;
double N;
public:
element (std::string,int,double);
double M (void) {return (Z+N);}
std::string NameF () {return (Name);}
};
element::element (std::string Name, int Z, double N) {
Name=Name;
Z=Z;
N=N;
}
int main () {
element H ("Hydrogen",1,1.);
element O ("Oxygen",8,8);
std::vector<element> H2O ={H,H,O};
std::cout<<"Mass of " <<O.NameF()<<" is: " << O.M() << std::endl;
std::cout<<H2O[1].NameF()<<std::endl;
return 0;
}
我无法从类中的对象中提取字符串。。。也许我甚至不能让他们进入课堂。标准构造函数对字符串的作用是这样的吗?我只想要一个我可以调用的对象的名称。这样做的正确方法是什么?
如果有任何帮助,我将不胜感激,
欢呼Niko
对于构造函数,您应该使用初始化列表编译器知道参数和成员之间的区别:
class element {
std::string Name;
int Z;
double N;
public:
element (std::string,int,double);
double M (void) {return (Z+N);}
std::string NameF () {return (Name);}
};
element::element (std::string Name, int Z, double N)
: Name(Name), Z(Z), N(N) // <- the compiler knows which is parameter and which is member
{
// no need to put anything here for this
}
否则,您可以使用this
:显式区分
void element::set_name(std::string const& Name)
{
// tell the compiler which is the member of `this`
// and which is the parameter
this->Name = Name;
}
如果使用成员的名称作为参数的名称,则需要通过this
指针访问该成员。
所以改变:
Name=Name;
至
this->Name = Name;
其他两个也是如此:
this->Z = Z;
this->N = N;
相关文章:
- 返回常量对象引用 (getter) 和仅返回字符串有什么区别?
- C++ 创建包含链表和字符串的对象的链接列表时出错
- 有没有办法让编译器在我放置字符串而不是 nlohmann::json 对象时抛出错误?
- 如何从文件中读取两个字符串和数字数组,并将它们存储在对象向量中
- 如何从字符串向量构造对象并避免复制?
- 在对象数组中搜索字符串并返回相应值的函数
- POCO C++对象到 JSON 字符串序列化
- 重载加法运算符(使用函数向对象添加字符串)
- 用字符串初始化我的类的对象
- C++ - 确定 const char* 是指向字符串文本对象还是动态对象
- 对象数组打印空白字符串
- 如何检索由带通配符的字符串索引的对象
- 在 c++ 中使用字符串变量选择静态类结构,而不带对象
- 在C++中,我想通过使用来自变量(例如字符串)的typename信息,从模板中定义一个类对象
- 如何删除作为C++联合的成员变量的字符串对象
- 如何定义此"if block"中其他无效输入的值,以便在c ++中将字符串转换为对象?
- C++-将对象(如字符串)映射到表中成员函数的正确方法
- C++指向对象的指针堆数组中,如何将字符串传递给特定对象?有一些代码请看一下:
- 如何提取由特定模式分开的JSON对象字符串
- C++ 不接受对象字符串中的@符号吗?似乎是地址问题?