我不明白为什么这个程序不能工作。我是C++的新手,在使用Java三年后转行。我认为Java中的错误消息毫无意义,但我在C++中得到的错误简直就是胡言乱语。这是我能真正理解的一个。
无论如何,我有一个程序,其中有一个矩形和正方形类。square类继承自rectangle类。我所有的类都在不同的文件中。
================================(main)
#include <iostream>
#include "Rectangle.h"
#include "Square.h"
using namespace std;
int main(){
Square sq;
}//end main================================(矩形.h)
#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=================================(Rectangle.cpp)
#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========================================(Square.h)
#ifndef SQUARE_H
#define SQUARE_H
class Square : public Rectangle
{
public:
Square();
};
#endif // SQUARE_H====================================(Square.cpp)
#include <iostream>
#include "Rectangle.h"
#include "Square.h"
using namespace std;
Square :: Square {
//super :: Square(4, 3);
cout << "This is bullshit";
};=======================================================
发布于 2013-06-11 11:58:08
您需要通过初始化列表传递父构造函数参数...
例如,如果默认矩形参数为(4,3):
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);
};发布于 2013-06-11 12:33:58
Square sq;
这将调用Square的默认构造函数,后者将首先调用基类Rectangle的默认构造函数。默认构造函数是没有参数的构造函数,或者如果它有参数,则所有参数都有默认值。如果您没有定义构造函数,C++编译器将为您提供一个默认构造函数。由于您已经定义了一个构造函数Rectangle (int, int),编译器将不会提供默认的构造函数。这就是错误的原因。
解决方案是为Rectangle类提供一个默认构造函数,方法是定义一个不带参数Rectangle()的构造函数,或者为现有构造函数的参数提供默认值,比如Rectangle(int x=10, int y=20)
https://stackoverflow.com/questions/17036266
复制相似问题