【问题标题】:Is a constructor called when passing objects as an argument?将对象作为参数传递时是否调用了构造函数?
【发布时间】:2013-12-03 23:35:34
【问题描述】:

我正在尝试编译必须使用 C++ 继承的旧代码。我已经修复了一段时间,但我放弃了这个错误:

class Operation{
    public:
    char *op;
    //Operation();
    Operation(char op[]){
    (*this).op = op;
    }
};

class Param : Operation{
    public:
    int value;

    Param(char op[], int value) : Operation(op){

    (*this).op=op;
    (*this).value=value;
    }

    int getValue(){
    return this->value;
    }

};


class MyBase{
    public:
    int valuea;
    int valueb;
    Operation operation;

    MyBase(int a, int b, Operation* op){
    valuea=a;
    valueb=b;
    operation=*op;
    }

    Operation* getSum(){};

    Operation* getRest(){};
};

class MyExtend : public MyBase{
    public:

    Param* getSum(){
        Param pam=new Param(this->valuea+this->valueb,"add");
        return pam;
    }

    Param* getRest(){
        Param pam=new Param(this->valuea-this->valueb,"rest");
        return pam;
    }
};

class Exec{

public int static main(args[] params){
    MyExtend ext=new MyExtend(6,4);
    cout << ext.getSum().getValue() << endl;
    cout << ext.getRest().getValue() << endl;
    return 0;
}

};

我正在关注

的错误

MyBase(int a, int b, Operation* op){

即:

错误:没有匹配的函数调用'Operation::Operation()'

我很惊讶,因为它看起来像是在检查 Operation 的默认构造函数。如果我重载默认构造函数,它可以工作,但我不明白为什么。如果我通过值或引用传递操作并不重要。你能给我一些关于这个功能的提示吗?我无法找到一致的回应。请忽略以下错误,因为我正在处理它们。

一切顺利。

【问题讨论】:

    标签: c++ constructor parameter-passing


    【解决方案1】:

    MyBase 包含一个名为operation 的成员,其类型为Operation,既不是指针也不是引用,因此编译器必须在构造MyBase 时构造该成员。该成员未在 MyBase 构造函数的(不存在的)初始化列表中初始化,因此编译器将尝试默认构造它;但是,Operation 没有默认构造函数,因此会出现错误。

    一个可能的解决方法是重写MyBase 的构造函数以使用初始化列表,如下所示:

    class MyBase
    {
      public:
        int valuea;
        int valueb;
        Operation operation;
    
        MyBase(int a, int b, Operation* op)
        : valuea(a)
        , valueb(b)
        , operation(*op) { }
    };
    

    但请注意,就目前而言,这将依赖于 default(即编译器提供的)复制构造函数,它可能无法执行您想要的操作,因此您可能应该提供显式复制ctor。

    【讨论】:

    • 明白。一个有力的答案。非常感谢。
    • +1,但我认为复制构造函数本身不会是一个改进。 OperationParam 的基类,并且 OP 几乎肯定会希望 Param 对象存储在 operation 中。智能指针类型可能是更好的选择,它不一定需要复制*op
    • 我使用 Code::Blocks 作为我的 IDE,因为它提供了许多编译器,但在运行时我得到:mingw32-g++.exe -o bin\Release\Tests.exe obj\Release\Exec。 o -s c:/program files/codeblocks/mingw/bin/../lib/gcc/mingw32/4.7.1/../../../libmingw32.a(main.o):main.c:( .text.startup+0xa7): undefined reference to `WinMain@16' collect2.exe: error: ld returned 1 exit status 进程以状态1终止(0分0秒)1个错误,0个警告(0分0秒) )
    • 我知道这不相关,但你知道会发生什么吗?
    • 我的主要功能是:int main(int argc, const char* argv[]) 我正在编译一个控制台应用程序,而不是一个 GUI。
    猜你喜欢
    • 2012-01-17
    • 1970-01-01
    • 2013-12-12
    • 2015-04-10
    • 1970-01-01
    • 2013-11-29
    • 2012-11-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多