using namespace std;
class car
{
private:
string name;
string brand;
int tspeed;
public:
car();
car(string name1,string brand1,int ip);
car(car &ref);
~car();
void disp();
};
car::car()
{
cout<<"default constructor invoked\n";
}
car::car(string name1, string brand1, int sp)
{
name=name1;
brand=brand1;
tspeed=sp;
cout<<"parameterised constructor invoked\n";
}
car::car(car &ref)
{
name=ref.name;
brand=ref.brand;
tspeed=ref.tspeed;
cout<<"copy constructor invoked\n";
}
car::~car()
{
cout<<"destructor invoked\n";
}
void car::disp()
{
cout<<"enter the name\n";
cin>>name;
cout<<"entr the brand\n";
cin>>brand;
cout<<"enter the top speed\n";
cin>>tspeed;
cout<<"name:"<<name<<endl;
cout<<"brand:"<<brand<<endl;
cout<<"top speed:"<<tspeed<<endl;
}
int main()
{
car c1,c2,c3;
c1.car();
c1.disp();
c2.car(" "," ",0);
c2.disp();
c3.car(c2);
c3.disp();
return 0;
}
--------------------配置:mingw5 - CUI发布,构建器类型:MinGW ---------------- ----
检查文件依赖性...
编译C:\ Users \ Joe \ Documents \ C-Free \ Temp \ Untitled1.cpp ...
[错误] C:\ Users \ Joe \ Documents \ C-Free \ Temp \ Untitled1.cpp:55:错误:无效使用`class car&#39;
[错误] C:\ Users \ Joe \ Documents \ C-Free \ Temp \ Untitled1.cpp:56:错误:`c1&#39;未在此范围内声明
[错误] C:\ Users \ Joe \ Documents \ C-Free \ Temp \ Untitled1.cpp:57:错误:`c2&#39;未在此范围内声明
[错误] C:\ Users \ Joe \ Documents \ C-Free \ Temp \ Untitled1.cpp:59:错误:`c3&#39;未在此范围内声明
[警告] C:\ Users \ Joe \ Documents \ C-Free \ Temp \ Untitled1.cpp:62:2:警告:文件末尾没有换行符
完成Make Untitled1:4个错误,1个警告
无效使用班车有什么错误?
答案 0 :(得分:2)
您在此处错误地使用Car
构造函数。相反,您的代码应该遵循:
car c2(" "," ",0);
您的代码也存在性能问题 - 您无需创建字符串副本。你的构造函数应该有以下签名:
car(std::string name, std::string brand, int tspeed) : name(name), brand(brand), tspeed(tspeed) {}
答案 1 :(得分:2)
该语言不允许使用语法:
c1.car();
c2.car(" "," ",0);
c3.car(c2);
构造类的实例。
您可以使用:
car c1; // Use the default constructor
car c2(" "," ",0); // Use the constructor with all the details.
car c3(c2); // Use the copy constructor.
或使用作业:
c2 = car(" "," ",0);
c3 = c2;
答案 2 :(得分:1)
在C ++中,构造函数的调用方式不同:编写Type name(argument1, ...)
。所以这就是你的意思:
int main()
{
car c1;
c1.disp();
car c2(" "," ",0);
c2.disp();
car c3(c2);
c3.disp();
return 0;
}