【发布时间】:2018-03-09 16:57:00
【问题描述】:
我要做什么?
我正在尝试在对象的默认构造函数中获取用户输入,并在复制构造函数中进行比较,如果前一个对象和当前对象具有相同的品牌名称。
有什么问题?
我无法调用同一个对象的默认构造函数和复制构造函数。
我的代码:
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
class Scooty {
int cc ;
string model, brand;
bool goodBrands();
public:
Scooty () : cc(0), model(""), brand("") {
cout << "\n Enter the following scooty details: \n\n";
cout << "\n \t Brand: ";
cin >> brand;
transform(brand.begin(), brand.end(), brand.begin(), :: tolower);
cout << "\n \t Model: ";
cin >> model;
transform(model.begin(), model.end(), model.begin(), :: tolower);
cout << "\n \t CC: ";
cin >> cc;
}
Scooty (Scooty &s) { if (brand == s.brand) cout << "You will get a discount!\n"; }
void computeDataAndPrint ();
};
bool Scooty :: goodBrands() {
if (brand == "honda" || brand == "tvs" || brand == "yamaha")
return true;
return false;
}
void Scooty :: computeDataAndPrint () {
if (cc > 109 && goodBrands())
cout << "\n Good Choice!\n";
else
cout << "\n Its okay!\n";
}
int main() {
Scooty s;
Scooty s1, s1(s) // This gives error
s.computeDataAndPrint();
return 0;
}
【问题讨论】:
-
但是,为什么?你不能多次构造东西。确定一个比较它们的函数就足够了吗?
-
我想你误解了复制构造函数的用途
-
这是否意味着一个对象一次只能调用一个构造函数?
-
您在“默认构造函数”和“复制构造函数”中所做的操作应移至 2 个单独的函数“getUserInput”和“checkDiscount”,并在使用默认构造函数构造对象后调用它们
-
@Doda:在 C++11 及更高版本中,是的(使用委托构造函数)。在早期版本中,没有。
标签: c++ copy-constructor default-constructor