理解C++类的麻烦
问题描述:
我有一个类和一个命名空间,我需要从另一个文件访问类的数据。 例子:理解C++类的麻烦
namespace A {
struct SMS{
string id;
Messages msg; //(an array of strings)
};
}
class Users{
public:
//ALL THE FUNCTIONS HERE TO MANAGE THE USER
private:
struct User{
string id_user;
SMS sms;
};
};
所以现在我要访问sms
以及阵列中,但我不能找到一种方法。 它应该是这样的吗?
User ada_lovelace;
return ada_lovelace.sms.msg[1];
或:
return ada_lovelace.A::sms.msg[1];?
答
答案取决于你要去哪里定义和使用ada_lovelace
。如果你要声明它的Users
类的方法中的一种或作为类中的一员,你应该定义用户为:
struct User{
string id_user;
A::SMS sms;
};
,你应该能够使用
return ada_lovelace.sms.msg[1];
但是,如果你想使用ada_lovelace
ouside Users
类的,你必须定义User
为大众创造这样的对象:
Users::User ada_lovelace;
答
检查下面的实现
namespace A {
struct SMS{
string id;
Messages msg; //(an array of strings)
};
}
//Namespace A ends here so if you want to use SMS in the class u need to mention it as A::SMS sms
class Users{
public:
//ALL THE FUNCTIONS HERE TO MANAGE THE USER
private:
struct User{
string id_user;
A::SMS sms; // Corrected here ------------
};
};
'A :: sms'会在'A'中寻找'sms'。 – chris
你需要显示一个更完整版本的'用户'。现在我们只知道'User'包含一个私有结构。 – NathanOliver
只要你声明用户'A :: User ada_lovelace;',你应该可以访问'ada_lovelace.sms.msg [1];'。此外,C++使用关键字'class',而不是'Class'。 – Rubens