C++ 错误:对';的调用没有匹配函数;矩形::矩形();
我不明白为什么这个程序不起作用。我是C++新手,三年后java转换。我认为java中的错误信息没有意义,但是C++中的错误只是直接的胡言乱语。这是我能真正理解的 总之,我有一个程序,有一个矩形和正方形的类。square类继承自矩形类。我所有的类都在不同的文件中 ==========================================================(主) ==========================================================(矩形.cpp) ==========================================================(Square.cpp)C++ 错误:对';的调用没有匹配函数;矩形::矩形();,c++,function,matching,C++,Function,Matching,我不明白为什么这个程序不起作用。我是C++新手,三年后java转换。我认为java中的错误信息没有意义,但是C++中的错误只是直接的胡言乱语。这是我能真正理解的 总之,我有一个程序,有一个矩形和正方形的类。square类继承自矩形类。我所有的类都在不同的文件中 ==========================================================(主) =========================================================
#包括
#包括“矩形.h”
#包括“Square.h”
使用名称空间std;
正方形{
//超级:正方形(4,3);
您需要通过初始化列表传递父构造函数参数
例如,如果默认矩形参数为(4,3):
和在头文件中:
class Square : public Rectangle
{
public:
Square(int len=4, int width=3);
};
sq;
这将调用默认的构造函数<代码>平方或代码>,它首先调用基类的默认构造函数:代码>矩形< /COD>。默认构造函数是一个没有参数的构造函数,或者如果它有参数,所有的参数都有默认值。如果没有DEC,C++编译器会为你提供一个默认的构造函数。定义了构造函数。由于您定义了构造函数
矩形(int,int)
,编译器将不提供默认构造函数。这就是错误的原因
解决方案是通过定义一个构造函数来为Rectangle
类提供默认构造函数,该构造函数不接受参数Rectangle()
,或者为现有构造函数的参数提供默认值,比如Rectangle(int x=10,int y=20)
C++没有super
关键字。它使用构造函数初始化列表进行初始化(除非在C++11中引入的类成员初始化中进行计数).重要提示:您使用的OOP错误。您刚刚演示了圆-椭圆问题的一种变体:天哪,非常感谢您,伙计。我已经做了将近一周了。=)
#ifndef RECTANGLE_H
#define RECTANGLE_H
class Rectangle{
public:
Rectangle (int, int);
void setLength (int);
void setWidth (int);
int getLength ();
int getWidth ();
int getArea ();
private:
int length;
int width;
};
#endif // RECTANGLE_H
#include <iostream>
#include "Rectangle.h"
#include "Square.h"
using namespace std;
Rectangle :: Rectangle (int len, int wid){
length = len;
width = wid;
}//end constructor
void Rectangle :: setLength (int l){
length = l;
}//end setLength
void Rectangle :: setWidth (int w){
width = w;
}//end setWidth
int Rectangle :: getLength (){
return length;
}//end getLength
int Rectangle :: getWidth (){
return width;
}//end getWidth
int Rectangle :: getArea (){
return length * width;
}//end getArea
#ifndef SQUARE_H
#define SQUARE_H
class Square : public Rectangle
{
public:
Square();
};
#endif // SQUARE_H
#include <iostream>
#include "Rectangle.h"
#include "Square.h"
using namespace std;
Square :: Square {
//super :: Square(4, 3);
cout << "This is bullshit";
};
Square :: Square( )
: Rectangle(4, 3)
{
//super :: Square(4, 3);
cout << "This is bullshit";
}
Square :: Square(int len, int wid)
: Rectangle(len, wid)
{
}
class Square : public Rectangle
{
public:
Square(int len=4, int width=3);
};