【问题标题】:"this" Cannot Be Used As A Function“this”不能用作函数
【发布时间】:2011-10-04 14:56:00
【问题描述】:

在 C++ 中,我试图模拟 Java 如何处理对其构造函数的调用。在我的 Java 代码中,如果我有 2 个不同的构造函数并且想要一个调用另一个,我只需使用 this 关键字。示例:

public Constructor1(String s1, String s2)
{
    //fun stuff here
}

public Constructor2(String s1)
{
    this("Testing", s1);
}

使用此代码,通过使用 Constructor2 实例化一个对象(传入单个字符串),它将只调用 Constructor1。这在 Java 中效果很好,但我怎样才能在 C++ 中获得类似的功能?当我使用 this 关键字时,它会抱怨并告诉我 'this' cannot be used as a function

【问题讨论】:

  • 你不能用 C++ 那样做,你需要做一些像 MyObject *x = new MyObject("Testing,s1")

标签: c++ class-constructors


【解决方案1】:

这将在 C++11 中通过构造函数委托实现:

class Foo {
public:
    Foo(std::string s1, std::string s2) {
        //fun stuff here
    }

    Foo(std::string s1) : Foo("Testing", s1) {}
};

【讨论】:

    【解决方案2】:

    你可以为这样的工作写一个init私有成员函数,如下所示:

    struct A
    {
       A(const string & s1,const string & s2)
       {
           init(s1,s2);
       }
       A(const string & s)
       {
          init("Testing", s);
       }
    private:
    
       void init(const string & s1,const string & s2)
       {
             //do the initialization
       }
    
    };
    

    【讨论】:

    • +1 用于将构造函数重载与默认初始化相结合。
    • string 参数应该是 std::string const &
    • @David:是的。那更好。已编辑。
    【解决方案3】:

    您无法在 C++ 中实现这一点。解决方法是使用默认参数创建单个构造函数。

    例如

    class Foo {
        public:
           Foo(char x, int y=0);  // this line combines the two constructors
           ...
     }; 
    

    或者,您可以使用包含公共代码的单独方法。然后在您的两个构造函数中,使用适当的参数调用辅助方法。

    【讨论】:

    • 这与 OP 想要的不一样。他想要Foo(0, x) 而不是Foo(x,0)
    • OP 给出的代码只是一个例子。我相信总的来说,他只是想要某种方式来调用不同的构造函数。但是,是的,在这种特殊情况下,您必须使用带有单独辅助方法的第二种解决方案。
    【解决方案4】:

    你要找的东西叫Constructor overloading

    【讨论】:

      【解决方案5】:

      另一种方式:

      Foo(int a){ *this = Foo(a,a); }
      Foo(int a, int b): _a(a), _b(b){}
      

      它效率不高,但与您想要的相似。但是我不建议这个选项,因为我上面的选项更好(在效率方面)。我刚刚发布此内容是为了展示一种不同的做法。

      【讨论】:

      • 人们期望赋值运算符负责释放被分配对象所持有的资源。小心使用它,不是因为任何可能的低效率,而是因为正确性。由于对象还没有完全构造好,资源分配应该释放,但可能还没有,会发生什么?
      • 是的,对不起,我没有提到我的假设。如果在 Foo 类中分配了动态内存,那么就有可能出现错误。但是在上面我假设 operator=(const Foo&) 使用了浅拷贝。
      猜你喜欢
      • 2021-04-06
      • 2011-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-09
      • 2021-06-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多