【问题标题】:Convert code by writing new function in C++ Builder [closed]通过在 C++ Builder 中编写新函数来转换代码 [关闭]
【发布时间】:2021-06-03 09:36:05
【问题描述】:

下面的程序运行良好,但在每个函数中都重复了相同的四行。把它变成一个函数,然后直接用值调用它。不需要变量。

void __fastcall TfrmMain::Num1()
{
String name = GetCurrentDir() + "\\first.exe";
if(FileExists(name))
  {
    ShellExecute(NULL, L"runas", name.c_str(), NULL, NULL, SW_SHOWNORMAL);
  }
  else
  {
    Message();
  }
 }

void __fastcall Main::Num2()
{
String name = GetCurrentDir() + "\\second.exe";
if(FileExists(name))
 {
   ShellExecute(NULL, L"runas", name.c_str(), NULL, NULL, SW_SHOWNORMAL);
 }
 else
 {
   Message();
 }
 }  

void __fastcall Main::Num3()
{
String name = GetCurrentDir() + "\\third.exe";
if(FileExists(name))
 {
   ShellExecute(NULL, L"runas", name.c_str(), NULL, NULL, SW_SHOWNORMAL);
 }
 else
 {
   Message();
 }
 }  

【问题讨论】:

  • 问题是什么?
  • 唯一的区别是要运行的程序的名称吗?然后将其作为参数传递给单个函数。
  • 顺便说一句,这应该更适合the code review SE site
  • @Someprogrammerdude,它不适合Code Review,因为它要求替换代码而不是审查实际代码。而且它还需要更多的上下文才能进行审查。

标签: c++ c++builder


【解决方案1】:

您需要编写一个以name 作为参数的函数,因此我提供了一个示例来说明其外观。

我已经删除了文件是否存在的检查,因为这不是唯一可以执行它的东西,即使文件是可执行的,由于很多原因它仍然可能无法执行它。相反,只需尝试执行它然后调查返回值。您需要将其转换为 int,如果 int 大于 32,则表示成功。

例子:

bool __fastcall RunAs(String name) {
    name = GetCurrentDir() + "/" + name;

    auto hInst = ShellExecute(nullptr, _T("runas"), name.c_str(),
                              nullptr, nullptr, SW_SHOWNORMAL);

    int rv = reinterpret_cast<int>(hInst);

    bool successful = rv > 32;

    if(not successful) {
        /*
        switch(rv) {
        case ERROR_FILE_NOT_FOUND: // one of the many possible errors
            // do something specific to this error
            break;
        }
        */
        Message();
    }

    // Make it possible for the calling functions to take action
    // if running the program failed:
    return successful; 
}

然后您可以将成员函数更改为:

void __fastcall TfrmMain::Num1() { RunAs("first.exe"); }
void __fastcall TfrmMain::Num2() { RunAs("second.exe"); }
void __fastcall TfrmMain::Num3() { RunAs("third.exe"); }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-28
    • 1970-01-01
    • 2011-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-12
    • 1970-01-01
    相关资源
    最近更新 更多