Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Access and Mutator Practice | Encapsulation Overview
C++ OOP

book
Access and Mutator Practice

Oppgave

Swipe to start coding

  • Finish an implementation of a class called Vault that simulates a secure vault for storing a message with a password.
    • Implement the get_message() method that should return the stored message if the provided password matches the vault's password otherwise return an empty string or some suitable indication.
    • Implement the set_message() method, which takes two parameters, a new message and the current password. This method should allow changing the message only if the current password matches the vault's password.
    • Implement the set_password() method that takes two parameters, a new password and the old password. It should change the vault's password to the new one if the old password matches the current password.

Løsning

cpp

solution

#include <iostream>

class Vault {
public:
Vault(std::string message, std::string password)
: message(message), password(password) {}
std::string get_message(std::string current_password)
{
return password == current_password ? message: "Denied";
}
void set_message(std::string new_message, std::string current_password)
{
if (password != current_password)
return;
message = new_message;
}
void set_password(std::string new_password, std::string old_password)
{
if (password != old_password)
return;
password = new_password;
}
private:
std::string message;
std::string password;
};

int main()
{
Vault vault("Gold", "c<>definity");
std::cout << vault.get_message("c<>definity") << ' ';

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 3. Kapittel 5
#include <iostream>

class Vault {
public:
Vault(std::string message, std::string password)
: message(message), password(password) {}
___ get_message(___ ___)
{
// Implement
}
void set_message(std::string new_message, std::string current_password)
{
// Implement
}
void set_password(std::string new_password, std::string old_password)
{
if (password != old_password)
return;
password = new_password;
}
private:
std::string message;
std::string password;
};

int main()
{
Vault vault("Gold", "c<>definity");
std::cout << vault.get_message("c<>definity") << ' ';
vault.set_message("Silver", "c<>definity");
vault.set_password("c<>delimited", "c<>definity");
std::cout << vault.get_message("c<>definity") << ' ';
toggle bottom row
We use cookies to make your experience better!
some-alt