C ++在另一个类构造函数中调用构造函数

时间:2018-06-21 10:24:49

标签: c++

Transaction t(name, x, Date d(a, b, c));这行代码中,此代码生成错误:expected primary-expression before 'd'|

调用构造函数并传递另一个构造函数调用有效的代码吗?

#include<iostream>
#include<cstring>

using namespace std;
class Date{
private:
    int a;
    int b;
    int c;
public:
    Date(int a =0, int b=0, int c =0){
        this->a= a;
        this->b = b;
        this->c = c;
    }

    int getA(){
        return a;
    }

    int getB(){
        return b;
    }

    int getC(){
        return c;
    }

    void setA(int a){
        this->a = a;
    }

    void setB(int b){
        this->b = b;
    }

    void setC(int c){
        this->c = c;
    }

};

class Transaction {
private:
    char name[30];
    char x[10];
    Date *d;
public:



    Transaction(char const *name = "", char const *x = "", const Date *d = 0) {
        strcpy(this->name, name);
        strcpy(this->x, x);
//        this->d.setA(d.getA());
//        this->d.setB(d.getB());
//        this->d.setC(d.getC());
    }

    Date *getDate() {
        return d;
    }

};

int main() {

    int a,b,c;
    char name[30];
    char x[10];

    a=1;
    b=2;
    c=3;

    cin>>name;
    cin>>x;

    Transaction t(name, x, Date d(a, b, c));

}

1 个答案:

答案 0 :(得分:3)

如果将Date d(a, b, c)放在自己的行上,它将定义类型为d的名为Date的对象。但是,不能将变量定义作为通用表达式。

可以使用例如创建任何类型的临时对象。 Date(a, b, c)

但是,这很大,但是您的Transaction构造函数出于某种原因想要指向Date对象的 pointer ,因此您无法真正创建临时对象反对并通过。相反,您必须定义一个变量,并将其作为指针传递给Transaction构造函数:

Date d(a, b, c);
Transaction t(name, x, &d);  // &d returns a pointer to d

由于Transaction对象想要一个指向Date对象的指针并存储该指针本身,而不是复制到其自己的Date对象中,因此必须注意传递的指针直到Transaction对象被销毁之前,构造函数保持有效。

对于像这样的简单事情,我真的建议您考虑通过值而不是作为指针传递Date对象。然后将成员变量也更改为对象。

也请考虑使用变量命名方案。一个好的变量名应该简短但要有描述性。以您的Date成员变量abc为例,它们是什么意思?如果半年后再使用此代码,您会明白它们的作用吗?

相关问题