大家好,最近在努力学习C++,但是遇见了一些问题,很希望懂的人士帮我解答下,这对于你们很简单吧,嘿嘿,谢谢了
代码如下:
#include<iostream>
using namespace std;
class Box{
public:
double length;
double heigth;
double width;
int d;
Box();
Box(double length1,double heigth1,double width1){
length=length1;
heigth=heigth1;
width=width1;
}
double volume(){
return length*heigth*width;
}
};//要有分号哦!
int main(){
Box firstBox(2.0,4.0,6.0);
firstBox.d=2;
cout<<endl
<<firstBox.length<<"\n"
<<firstBox.heigth<<"\n"
<<firstBox.width<<"\n"
<<firstBox.d
<<endl;
cout<<firstBox.volume();
Box smallBox;
smallBox.length=10.0;
smallBox.heigth=5.0;
smallBox.width=4.0;
cout<<endl;
cout<<smallBox.length<<"\n"
<<smallBox.heigth<<"\n"
<<smallBox.width<<"\n"
<<smallBox.volume()
<<endl;
return 0;
}
在Dev_C++5.6.1上编译的,出现了如下:
C:\Users\ADMINI~1\AppData\Local\Temp\ccgxkOkf.o lei1.cpp:(.text+0x10f): undefined reference to `Box::Box()'
D:\Dev-Cpp\大二C\collect2.exe [Error] ld returned 1 exit status
我在百度上搜了很多,但很不理解,希望各位帮忙解答下。谢谢了
因为你编写的Box smallBox;需要使用到无参构造函数,但是你已经提供了一个带参数的构造函数,因此编译器将不会为你提供无参构造函数,即默认构造函数,你只需在类定义加上Box(){},即显式定义一个无参构造函数就可以了。
另外你原来代码中有个Box(),这个只是声明,没有定义,但是你Box smallBox;这个需要使用这个函数,但连接器找不到这个函数的入口,因此也会报错的。
我好像找到错了,class Box里面有个默认的构造函数Box,所以只需将“Box()”改为“Box(){}”就好了 但是呢 我不知道为什么。。。。。