Default constructor not being called c++ OOP

2020-04-20 06:11发布

So I'm making a program in c++ to handle vectors, and it's mostly there, but I just wanted to test it, so I have this:

class vector3 {
    protected: 
        double x,y,z;  

    public: 
        // Default 3 vector Constructor
        vector3() { 
            cout << "Default constructor called." << endl;
            x=y=z=0; 
        }
    vector3(double xin, double yin, double zin) {
        cout << "parametrised constructor called." << endl;
        x=xin;
        y=yin;
        z=zin;
    }
};

(there's more stuff, things for << etc)

and as main() I have:

int main() {

    vector3 vec1();
    cout << "Vector 1: " << vec1 << endl;

    vector3 vec2(0, 0, 0);
    cout << "Vector 2: " << vec2 << endl;
    return 0;
}

And it gives the output:

Vector 1: 1
Parametrised constructor called.
Vector 2: (0,0,0)
Destroying 3 vector

But shouldn't they give the same output? Am I missing something really obvious?

Edit: There's a warning when compiling that says:

test.cpp: In function ‘int main()’:
test.cpp:233:26: warning: the address of ‘vector3 vec1()’ will always evaluate as ‘true’ [-Waddress]
  cout << "Vector 1: " << vec1 << endl;

1条回答
神经病院院长
2楼-- · 2020-04-20 06:18
vector3 vec1();

You're declaring a function here, and displaying a function pointer. Use:

vector3 vec1;
查看更多
登录 后发表回答