如何在c++中返回类中对象的字符串

How can I return a String of an object in a class in c++?

本文关键字:对象 字符串 返回 c++      更新时间:2023-10-16

我想访问一个字符串,这个字符串是我的类的一部分,但我似乎无法使它工作。下面是示例代码:

#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;