声明用户账户类”CAccount”,用于保存用户的账号和密码,使用引用对成员变量进行赋值
时间: 2024-04-16 14:29:55 浏览: 23
在C++中声明一个用户账户类"CAccount",并使用引用对成员变量进行赋值的示例代码如下:
```cpp
#include <iostream>
#include <string>
class CAccount {
public:
CAccount(std::string& account, std::string& password) : m_account(account), m_password(password) {}
void displayAccountInfo() {
std::cout << "Account: " << m_account << std::endl;
std::cout << "Password: " << m_password << std::endl;
}
private:
std::string& m_account;
std::string& m_password;
};
int main() {
std::string account = "example_account";
std::string password = "example_password";
CAccount userAccount(account, password);
userAccount.displayAccountInfo();
return 0;
}
```
在上面的示例代码中,我们定义了一个名为"CAccount"的类,该类具有两个成员变量:m_account和m_password,它们都是std::string类型的引用。
在构造函数中,我们通过引用参数将传入的account和password值赋给成员变量m_account和m_password。
然后,我们定义了一个displayAccountInfo()函数,用于显示账户信息。
在主函数中,我们创建了一个名为userAccount的CAccount对象,并将account和password作为引用参数传递给构造函数进行赋值。
最后,我们调用displayAccountInfo()函数来显示用户账户信息。
请注意,由于成员变量是引用类型,确保在使用时引用所指向的对象仍然有效。