Default constructor not being called c++ OOP

99封情书 提交于 2019-12-04 05:04:01

问题


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:


vector3 vec1();

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

vector3 vec1;


来源:https://stackoverflow.com/questions/22547477/default-constructor-not-being-called-c-oop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!