我正在寻找一种在调用一个函数时创建类的新实例的方法,但是仍然可以访问其他函数内部的对象。
我曾考虑过在main()中创建该类的实例,并从一个函数中对其进行重写,但是当代码运行时,它似乎没有任何作用。
这段代码是为了想象我想要完成的事情。
#include <iostream>
class Account {
private:
int a;
public:
int b;
};
void createAccount(){
// i want to create a class instance under certain conditions (function
//invoked)
Account myAccount();
};
void getAccountInt(){
//and access the newly created instance here in some way
std::cout << myAccount.b << endl;
};
int main(){
return 0;
}
我不擅长问这类事情,这是我能想到的最好的例子。
答案 0 :(得分:0)
您可以使用Scott Meyer的单例以延迟方式创建全局实例。这会起作用,但设计值得怀疑:
auto global_account() -> Account& {
static auto account = Account{};
return account;
}
void create_account() {
auto& account = global_account();
// set account stuff
};
void get_account_int() {
auto& account = global_account();
std::cout << account.b << std::endl;
};
但是正确的解决方案是将帐户传递给需要您主要功能或其他功能之一的功能:
auto create_account() -> Account {
auto account = Account{};
// set account stuff
return account;
};
void get_account_int(Account& account) {
std::cout << account.b << std::endl;
};
auto main() -> int {
auto account = create_account();
auto acc_int = get_account_int(account);
}
答案 1 :(得分:0)
您的功能似乎已经存在,可以决定是否要创建一个帐户(基于您的评论)。在这种情况下,不必实际创建它。您只需要它来做出决定即可,您的代码可以对此做出反应。
#include <iostream>
class Account {
private:
int b;
public:
Account() : b(0) {};
int getAccountInt() const { return b; }
};
bool shouldCreateAccount() {
return true; // you handle the decision here
}
int main() {
if (shouldCreateAccount()) {
Account myAccount;
std::cout << myAccount.getAccountInt() << std::endl;
}
return 0;
}
更一般的原则是https://en.cppreference.com/w/cpp/language/raii如果存在一个Account对象,则该对象必须有效。请注意,如果我们决定创建一个帐户,那么我们就有一个,如果不决定创建一个帐户,那么这里什么也没有。当您涵盖“范围”时,这将更加有意义。
我对为什么您的代码不起作用的观点是,当您没有有效的帐户时,您试图拥有一个帐户,这违反了RAII。尽管有时候我确实有一种奇怪的看待事物的方式。