如何访问C++中实例的成员

如何访问C++中实例的成员,c++,C++,尝试访问类的私有成员时出错。我的目标是创建一个类,创建一个对象,然后访问输入到其中的内容 因此,我为我的声明创建了一个User1.hpp文件 class user1 { private: string username1; string email; string mobile; public: user1(string Myfirstname , string emailaddress , string mobile); //constructor

尝试访问类的私有成员时出错。我的目标是创建一个类,创建一个对象,然后访问输入到其中的内容

因此,我为我的声明创建了一个User1.hpp文件

class user1 {

private:
    string username1;
    string email;
    string mobile;
    
public:
    user1(string Myfirstname , string emailaddress , string mobile); //constructor

};

在我的User1.cpp文件中,我实现了这个类

user1::user1(string Myfirstname , string emailaddress , string mobile)
{
    user1::username1 = Myfirstname;
    user1::email = emailaddress;
    
}
然后在main.cpp中,我创建了第一个对象并输入了一些随机数据

user1 firstman {"John" , "john1@email.com" , "011000000"};

现在,当我想查看main.cpp中的firstman电子邮件时,我尝试了以下方法:

cout<<"Created "<< firstman.username1 <<" !"<<endl;

这给了我一个私人成员的错误。访问该数据的最佳方法是什么?

私有成员意味着不能从类外访问。您可以将username1设置为public并设置为const:

#include <iostream>
#include <string>

class user1 {
    
public:
    const std::string username1;
    user1(std::string Myfirstname, std::string emailaddress, std::string); //constructor

private:
    std::string email;
    std::string mobile;

};

user1::user1(std::string Myfirstname, std::string emailaddress, std::string): username1(Myfirstname), email(emailaddress) {}

int main() {
    user1 firstman {"John" , "john1@email.com" , "011000000"};
    
    std::cout << "Created " << firstman.username1 << " !\n";
}

这是私有成员的想法,不应从类外访问它们。如果您希望能够访问它们,请不要将它们设置为私有的?在您的情况下,您可能需要为您的私有字段定义公共getter,例如string getEmail{return This->email;}问题是您认为私有的用途是什么?它的工作正是它应该的。请开始阅读任何关于C++的书,第1页,明白了!感谢Thomas澄清私有/公共和使用constfact,提供getter函数可能是更好的解决方案,请参见上面@Yang Hanlin的评论。如果类中有常量成员,请使用这些类的实例,例如,在容器std::vector、std::map。。。dasmy实际上,提供一个getter函数可能是更好的解决方案。如果没有必要,应避免使用IMHO吸气剂。在一些公司中,它已经成为一种反模式,因为它经常污染类,特别是当存在一对微不足道的getter和setter时。@ThomasSablik:原则上,我同意getter可能是非常烦人的样板代码,尤其是对于简单的数据结构,我个人更喜欢公共成员。由于有点过时,我使用struct而不是class来处理这些情况。然而,我确实认为这对编程初学者来说不是一个好的建议,因为这样很快就会使封装无效。@dasmy