Visual C++: No default constructor

两盒软妹~` 提交于 2019-12-02 03:39:40

问题


I've looked at a couple other questions asking this, but mine seems to be a lot simpler of a case then the ones I've been through, so I'll ask my case for this.

Learn.h:

#ifndef LEARN_H
#define LEARN_H

class Learn
{
public:
    Learn(int x);
    ~Learn();

private:
    const int favourite;
};

#endif

Learn.cpp:

#include "Learn.h"
#include <iostream>
using namespace std;

Learn::Learn(int x=0): favourite(x)
{
    cout << "Constructor" << endl;
}

Learn::~Learn()
{
    cout << "Destructor" << endl;
}

Source.cpp:

#include <iostream>
#include "Learn.h"
using namespace std;

int main() {
    cout << "What's your favourite integer? "; 
    int x; cin >> x;
    Learn(0);

    system("PAUSE");
}

The above code in itself does not output any error.

However, I do get a couple errors after I replace Learn(0) with Learn(x). They are:

  • Error E0291: no default constructor exists for class Learn
  • Error C2371: 'x' : redefinition; different basic types
  • Error C2512: 'Learn' : no appropriate default constructor available

Any reason for this? I really want to actually input the integer variable x inside it rather than the 0. I know this is only practice and I'm new to this, but really, I'm a little confused as to why this doesn't work.

Any help would be appreciated, thanks.


回答1:


Parsing issue:

Learn(x);

is parsed as

Learn x;

You should use

Learn{x};

to build your temporary or

Learn some_name{x};
//or
Learn some_name(x);

if you want an actual object.




回答2:


Okay, I figured out the problem I was having. I didn't realize that the call is done as part of an object assignment. The notation in C++ seems to be a bit different that way.

So Learn(x) should be replaced with Learn obj(x) apparently.

This notation is a little off from other programming languages where you can usually write className(inputs) variableName.




回答3:


I had similar code and came up with a different errors because I was compiling with Linux in a terminal. My errors were:

error: conflicting declaration 'myObject str' 
error: 'str' has a previous declaration as 'const string  str'

when I tried myObject(str);

Sure Learn{x}; (and in my case myObject{str};) will successfully compile, but it creates a temporary object, then destroys it in the same line.

This is not what I wanted to do. So an alternative solution is to create a new object like:

Learn var_name = new Learn(x);

This way you can reference it for future use.



来源:https://stackoverflow.com/questions/46454134/visual-c-no-default-constructor

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